From 991a8316f8ed81b9bb9e4a31d3826c238d742a3e Mon Sep 17 00:00:00 2001 From: David Reed Date: Sun, 5 Feb 2023 19:57:19 -0500 Subject: [PATCH] Make dynamic imports relative to the importing script --- src/rewrite/index.js | 14 ++++++++++++++ src/rewrite/rewrite.script.js | 4 +++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/rewrite/index.js b/src/rewrite/index.js index 4f1986e..4354a23 100644 --- a/src/rewrite/index.js +++ b/src/rewrite/index.js @@ -51,6 +51,7 @@ class Ultraviolet { //this.urlRegex = /^(#|about:|data:|mailto:|javascript:)/; this.urlRegex = /^(#|about:|data:|mailto:)/; this.rewriteUrl = options.rewriteUrl || this.rewriteUrl; + this.rewriteImport = options.rewriteImport || this.rewriteImport; this.sourceUrl = options.sourceUrl || this.sourceUrl; this.encodeUrl = options.encodeUrl || this.encodeUrl; this.decodeUrl = options.decodeUrl || this.decodeUrl; @@ -97,6 +98,19 @@ class Ultraviolet { setCookie, }; } + /** + * + * @param {string} str Script being imported + * @param {string} src Script that is importing + * @param {*} meta + */ + rewriteImport(str, src, meta = this.meta) { + // use importiing script as the base + return this.rewriteUrl(str, { + ...meta, + base: src, + }); + } rewriteUrl(str, meta = this.meta) { str = new String(str).trim(); if (!str || this.urlRegex.test(str)) return str; diff --git a/src/rewrite/rewrite.script.js b/src/rewrite/rewrite.script.js index 5b83d2f..a9d1dde 100644 --- a/src/rewrite/rewrite.script.js +++ b/src/rewrite/rewrite.script.js @@ -263,7 +263,9 @@ function dynamicImport(ctx) { js.on(Syntax.ImportExpression, (node, data, type) => { if (type !== 'rewrite') return false; data.changes.push({ - node: '__uv.rewriteUrl(', + // pass script URL to dynamicImport + // import() is always relative to script URL + node: `__uv.rewriteImport(${JSON.stringify(ctx.meta.url)},`, start: node.source.start, end: node.source.start, });