Make dynamic imports relative to the importing script

This commit is contained in:
David Reed 2023-02-05 19:57:19 -05:00
parent 9ed1fddf25
commit 991a8316f8
No known key found for this signature in database
GPG key ID: 2211691D8A1EE72F
2 changed files with 17 additions and 1 deletions

View file

@ -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;

View file

@ -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,
});