Skip to content

Commit

Permalink
fix(dynamic-import-vars): exclude external imports (#1193)
Browse files Browse the repository at this point in the history
* fix: exclude external imports

* test: add test

* chore: change to http

* chore: feedback comments

* refactor: review comments
  • Loading branch information
thepassle committed Aug 2, 2022
1 parent add3a35 commit 550f2c8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
19 changes: 18 additions & 1 deletion packages/dynamic-import-vars/src/dynamic-import-to-glob.js
Expand Up @@ -61,11 +61,28 @@ function expressionToGlob(node) {
}
}

const defaultProtocol = 'file:';
const ignoredProtocols = ['data:', 'http:', 'https:'];

function shouldIgnore(glob) {
const containsAsterisk = glob.includes('*');

const globURL = new URL(glob, defaultProtocol);

const containsIgnoredProtocol = ignoredProtocols.some(
(ignoredProtocol) => ignoredProtocol === globURL.protocol
);

return !containsAsterisk || containsIgnoredProtocol;
}

export function dynamicImportToGlob(node, sourceString) {
let glob = expressionToGlob(node);
if (!glob.includes('*') || glob.startsWith('data:')) {

if (shouldIgnore(glob)) {
return null;
}

glob = glob.replace(/\*\*/g, '*');

if (glob.startsWith('*')) {
Expand Down
Expand Up @@ -17,6 +17,24 @@ test('template literal with variable filename', (t) => {
t.is(glob, './foo/*.js');
});

test('external', (t) => {
const ast = CustomParser.parse('import(`https://some.cdn.com/package/${version}/index.js`);', {
sourceType: 'module'
});

const glob = dynamicImportToGlob(ast.body[0].expression.arguments[0]);
t.is(glob, null);
});

test('external - leaves bare module specifiers starting with https in tact', (t) => {
const ast = CustomParser.parse('import("http_utils");', {
sourceType: 'module'
});

const glob = dynamicImportToGlob(ast.body[0].expression.arguments[0]);
t.is(glob, null);
});

test('data uri', (t) => {
const ast = CustomParser.parse('import(`data:${bar}`);', {
sourceType: 'module'
Expand Down

0 comments on commit 550f2c8

Please sign in to comment.