Skip to content

Commit

Permalink
Fix wrong offset with comments in dynamic imports
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Aug 31, 2021
1 parent 3917d95 commit 778ee03
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/proud-shoes-explode.md
@@ -0,0 +1,5 @@
---
'wmr': patch
---

Fix incorrectly transformed dynamic import statements when there was a comment in front of the specifier (`import(/* foo */ 'my-module')`)
7 changes: 7 additions & 0 deletions packages/wmr/src/lib/transform-imports.js
Expand Up @@ -80,11 +80,18 @@ export async function transformImports(code, id, { resolveImportMeta, resolveId,
// `slice(item.d, item.s)` gives us "import(" to implement this.

// Strip comments - these are usually Webpack magic comments.
let originalSpec = spec;
spec = spec
.replace(/\/\*[\s\S]*\*\//g, '')
.replace(/^\s*\/\/.*$/gm, '')
.trim();

// Update start position if we stripped leading characters
if (originalSpec.length !== spec.length) {
// @ts-ignore
item.s += originalSpec.indexOf(spec);
}

// For dynamic imports, spec is a JavaScript expression.
// We need to try to convert it to a specifier, or bail if it's not static.
quote = (spec.match(/^\s*(['"`])/) || [])[1];
Expand Down
@@ -0,0 +1,2 @@
// @ts-ignore
const About = lazy(() => import(/* webpackChunkName: foo */ 'it_works'));
@@ -0,0 +1,2 @@
// @ts-ignore
const About = lazy(() => import(/* webpackChunkName: foo */ 'foo'));
13 changes: 13 additions & 0 deletions packages/wmr/test/transform-imports.test.js
Expand Up @@ -92,6 +92,19 @@ describe('transformImports', () => {
});
expect(result.code).toEqual(expected);
});

it('should transform imports with comments', async () => {
const code = await readFile('dynamic-import-comment.js');
const expected = await readFile('dynamic-import-comment.expected.js');
const result = await transformImports(code, 'my-test', {
resolveDynamicImport(id) {
if (id === 'foo') {
return 'it_works';
}
}
});
expect(result.code).toEqual(expected);
});
});

describe('import.meta', () => {
Expand Down

0 comments on commit 778ee03

Please sign in to comment.