Skip to content

Commit

Permalink
fix(esm-shim): do not insert shims at import literal (rollup#1696)
Browse files Browse the repository at this point in the history
* fix: update regex to do not match new line in specifier group

* test: add testcases and update snapshot
  • Loading branch information
younggglcy committed Jun 6, 2024
1 parent 2a19079 commit 26bebcd
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/esm-shim/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ const require = cjsModule.createRequire(import.meta.url);
`;

export const ESMStaticImportRegex =
/(?<=\s|^|;)import\s*([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm;
/(?<=\s|^|;)import\s*([\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"\n]*[^\s"](?=\s*")|(?<='\s*)[^'\n]*[^\s'](?=\s*'))\s*["'][\s;]*/gm;
6 changes: 6 additions & 0 deletions packages/esm-shim/test/fixtures/cjs-import-literal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const dn = __dirname;

module.exports = {
keyword: ' import',
dn
};
20 changes: 20 additions & 0 deletions packages/esm-shim/test/snapshots/test.js.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,23 @@ Generated by [AVA](https://avajs.dev).
␊
export { c, child, s };␊
`

## inject cjs shim should not break on valid js object with `import` literal value

> Snapshot 1
`␊
// -- Shims --␊
import cjsUrl from 'node:url';␊
import cjsPath from 'node:path';␊
import cjsModule from 'node:module';␊
const __filename = cjsUrl.fileURLToPath(import.meta.url);␊
const __dirname = cjsPath.dirname(__filename);␊
const require = cjsModule.createRequire(import.meta.url);␊
const dn = __dirname;␊
␊
module.exports = {␊
keyword: ' import',␊
dn␊
};␊
`
Binary file modified packages/esm-shim/test/snapshots/test.js.snap
Binary file not shown.
16 changes: 16 additions & 0 deletions packages/esm-shim/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,19 @@ test.serial('inject cjs shim for esm output with multiple import statements', as
t.snapshot(output.code);
t.falsy(output.map);
});

// see issue #1649 https://github.com/rollup/plugins/issues/1649
test.serial(
'inject cjs shim should not break on valid js object with `import` literal value',
async (t) => {
const bundle = await rollup({
input: 'test/fixtures/cjs-import-literal.js',
plugins: [esmShim()]
});
const result = await bundle.generate({ format: 'es' });
t.is(result.output.length, 1);
const [output] = result.output;
t.snapshot(output.code);
t.falsy(output.map);
}
);

0 comments on commit 26bebcd

Please sign in to comment.