Skip to content

Commit eb07c7c

Browse files
committed
feat: support template literals for import() and require()
resolves #141
1 parent 53cb80b commit eb07c7c

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

plugin/index.js

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,34 @@ const replacePrefix = (path, opts = [], sourceFile) => {
3333
return path;
3434
};
3535

36+
const replacePrefixStrOrQuasi = (node, opts, sourceFile) => {
37+
// String literal
38+
if (typeof node === 'string') {
39+
return replacePrefix(node, opts, sourceFile);
40+
}
41+
// Template literal quasi
42+
else if (node && typeof node.cooked === 'string') {
43+
return {
44+
...node,
45+
cooked: replacePrefix(node.cooked, opts, sourceFile),
46+
raw: replacePrefix(node.raw, opts, sourceFile),
47+
};
48+
} else {
49+
return node;
50+
}
51+
};
52+
3653
/**
3754
* Recursively traverses binary expressions to find the first `StringLiteral` if any.
3855
* @param {Object} t Babel types
3956
* @param {Node} arg a Babel node
4057
* @return {StringLiteral?}
4158
*/
4259
const traverseExpression = (t, arg) => {
60+
if (t.isTemplateLiteral(arg)) {
61+
return arg.quasis[0];
62+
}
63+
4364
if (t.isStringLiteral(arg)) {
4465
return arg;
4566
}
@@ -67,7 +88,7 @@ export default ({ types: t }) => {
6788
const firstArg = traverseExpression(t, args[0]);
6889

6990
if (firstArg) {
70-
firstArg.value = replacePrefix(
91+
firstArg.value = replacePrefixStrOrQuasi(
7192
firstArg.value,
7293
state.opts,
7394
state.file.opts.filename,

test/plugin.spec.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ describe('Babel Root Import - Plugin', () => {
3131
});
3232

3333
it('transforms for import() syntax', () => {
34-
const targetRequire = slash(`/some/example.js`);
34+
const targetRequire = slash(`'./some/example.js'`);
3535
const transformed = babelTransform(
3636
"var SomeExample = import('~/some/example.js');",
3737
{
@@ -42,6 +42,15 @@ describe('Babel Root Import - Plugin', () => {
4242
expect(transformed.code).to.contain(targetRequire);
4343
});
4444

45+
it('transforms for import() syntax with template literal', () => {
46+
const targetRequire = slash('`./some/${foo}`');
47+
const transformed = babelTransform('var SomeExample = import(`~/some/${foo}`);', {
48+
plugins: [importSyntaxPlugin, BabelRootImportPlugin],
49+
});
50+
51+
expect(transformed.code).to.contain(targetRequire);
52+
});
53+
4554
it('transforms for custom functions', () => {
4655
const targetRequire = slash(`/some/example.js`);
4756
const transformed = babelTransform(

0 commit comments

Comments
 (0)