Skip to content

fix: inline import.meta.url shims in CJS #275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 4 additions & 19 deletions packages/core/src/plugins/cjsShim.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { type RsbuildPlugin, rspack } from '@rsbuild/core';
import type { RsbuildPlugin } from '@rsbuild/core';

const importMetaUrlShim = `var __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
const importMetaUrlShim = `/*#__PURE__*/ (function () {
return typeof document === 'undefined'
? new (require('url'.replace('', '')).URL)('file:' + __filename).href
: (document.currentScript && document.currentScript.src) ||
new URL('main.js', document.baseURI).href;
})();
`;
})()`;

// This Rsbuild plugin will shim `import.meta.url` for CommonJS modules.
// - Replace `import.meta.url` with `importMetaUrl`.
Expand All @@ -19,22 +18,8 @@ export const pluginCjsShim = (): RsbuildPlugin => ({
api.modifyEnvironmentConfig((config) => {
config.source.define = {
...config.source.define,
'import.meta.url': '__rslib_import_meta_url__',
'import.meta.url': importMetaUrlShim,
};
});

api.modifyRspackConfig((config) => {
config.plugins ??= [];
config.plugins.push(
new rspack.BannerPlugin({
banner: importMetaUrlShim,
// Just before minify stage, to perform tree shaking.
stage: rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE - 1,
raw: true,
footer: true,
include: /\.(js|cjs)$/,
}),
);
});
},
});
4 changes: 2 additions & 2 deletions tests/integration/require/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ test('require.resolve', async () => {
];

const cjsStatements = [
'const _require = (0, external_node_module_namespaceObject.createRequire)(__rslib_import_meta_url__)',
'const _require = (0, external_node_module_namespaceObject.createRequire)(',
];

for (const statement of [...statements, ...esmStatements]) {
Expand Down Expand Up @@ -52,7 +52,7 @@ test('require dynamic', async () => {
];

const cjsStatements = [
'const _require = (0, external_node_module_namespaceObject.createRequire)(__rslib_import_meta_url__)',
'const _require = (0, external_node_module_namespaceObject.createRequire)(',
];

for (const statement of [...statements, ...esmStatements]) {
Expand Down
7 changes: 4 additions & 3 deletions tests/integration/shims/cjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const foo = () => {
console.log(import.meta.url);
};
const url = import.meta.url;
const readUrl = url;

export default readUrl;
22 changes: 9 additions & 13 deletions tests/integration/shims/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import { buildAndGetResults } from 'test-helper';
import { describe, expect, test } from 'vitest';

Expand All @@ -21,25 +22,20 @@ test('shims for __dirname and __filename in ESM', async () => {
describe('shims for `import.meta.url` in CJS', () => {
test('CJS should apply shims', async () => {
const fixturePath = join(__dirname, 'cjs');
const { entries } = await buildAndGetResults(fixturePath);
for (const shim of [
`var __rslib_import_meta_url__ = /*#__PURE__*/ function() {
return 'undefined' == typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
}();`,
'console.log(__rslib_import_meta_url__);',
]) {
expect(entries.cjs).toContain(shim);
}
const { entryFiles } = await buildAndGetResults(fixturePath);
const exported = await import(entryFiles.cjs);
const fileUrl = pathToFileURL(entryFiles.cjs).href;
expect(exported.default).toBe(fileUrl);
});

test('ESM should not be affected by CJS shims configuration', async () => {
const fixturePath = join(__dirname, 'cjs');
const { entries } = await buildAndGetResults(fixturePath);
expect(entries.esm).toMatchInlineSnapshot(`
"const foo = ()=>{
console.log(import.meta.url);
};
export { foo };
"const url = import.meta.url;
const readUrl = url;
/* harmony default export */ const src = readUrl;
export { src as default };
"
`);
});
Expand Down
Loading