Skip to content

Commit 80f583f

Browse files
authored
fix(shims): CJS shims should only affect chunk assets (#787)
1 parent 2820e28 commit 80f583f

File tree

9 files changed

+65
-15
lines changed

9 files changed

+65
-15
lines changed

packages/core/src/plugins/EntryChunkPlugin.ts

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,17 @@ import {
1212
SHEBANG_PREFIX,
1313
SHEBANG_REGEX,
1414
} from '../constant';
15-
import { importMetaUrlShim } from './shims';
1615
const require = createRequire(import.meta.url);
1716

1817
const PLUGIN_NAME = 'rsbuild:lib-entry-chunk';
1918
const LOADER_NAME = 'rsbuild:lib-entry-module';
19+
const IMPORT_META_URL_SHIM = `const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
20+
return typeof document === 'undefined'
21+
? new (require('url'.replace('', '')).URL)('file:' + __filename).href
22+
: (document.currentScript && document.currentScript.src) ||
23+
new URL('main.js', document.baseURI).href;
24+
})();
25+
`;
2026

2127
const matchFirstLine = (source: string, regex: RegExp): string | false => {
2228
const lineBreakPos = source.match(/(\r\n|\n)/);
@@ -32,6 +38,8 @@ const matchFirstLine = (source: string, regex: RegExp): string | false => {
3238
class EntryChunkPlugin {
3339
private reactDirectives: Record<string, string> = {};
3440

41+
private shimsInjectedAssets: Set<string> = new Set();
42+
3543
private shebangChmod = 0o755;
3644
private shebangEntries: Record<string, string> = {};
3745
private shebangInjectedAssets: Set<string> = new Set();
@@ -101,6 +109,8 @@ class EntryChunkPlugin {
101109
const name = chunk.name;
102110
if (!name) return;
103111

112+
this.shimsInjectedAssets.add(filename);
113+
104114
const shebangEntry = this.shebangEntries[name];
105115
if (shebangEntry) {
106116
this.shebangEntries[filename] = shebangEntry;
@@ -117,9 +127,13 @@ class EntryChunkPlugin {
117127
compilation.hooks.processAssets.tap(PLUGIN_NAME, (assets) => {
118128
if (!this.enabledImportMetaUrlShim) return;
119129

120-
const chunkAsset = Object.keys(assets).filter((name) =>
121-
JS_EXTENSIONS_PATTERN.test(name),
122-
);
130+
const chunkAsset = Object.keys(assets).filter((name) => {
131+
return (
132+
JS_EXTENSIONS_PATTERN.test(name) &&
133+
this.shimsInjectedAssets.has(name)
134+
);
135+
});
136+
123137
for (const name of chunkAsset) {
124138
compilation.updateAsset(name, (old) => {
125139
const oldSource = old.source().toString();
@@ -131,10 +145,10 @@ class EntryChunkPlugin {
131145
replaceSource.replace(
132146
0,
133147
11, // 'use strict;'.length,
134-
`"use strict";\n${importMetaUrlShim}`,
148+
`"use strict";\n${IMPORT_META_URL_SHIM}`,
135149
);
136150
} else {
137-
replaceSource.insert(0, importMetaUrlShim);
151+
replaceSource.insert(0, IMPORT_META_URL_SHIM);
138152
}
139153

140154
return replaceSource;

packages/core/src/plugins/shims.ts

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,5 @@
11
import { type RsbuildPlugin, rspack } from '@rsbuild/core';
22

3-
// The shim will be injected in PostEntryPlugin.
4-
export const importMetaUrlShim = `const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
5-
return typeof document === 'undefined'
6-
? new (require('url'.replace('', '')).URL)('file:' + __filename).href
7-
: (document.currentScript && document.currentScript.src) ||
8-
new URL('main.js', document.baseURI).href;
9-
})();
10-
`;
11-
123
// This Rsbuild plugin will shim `import.meta.url` for CommonJS modules.
134
// - Replace `import.meta.url` with `importMetaUrl`.
145
// - Inject `importMetaUrl` to the end of the module (can't inject at the beginning because of `"use strict";`).

packages/core/tests/__snapshots__/config.test.ts.snap

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ exports[`Should compose create Rsbuild config correctly > Merge Rsbuild config i
231231
"shebangChmod": 493,
232232
"shebangEntries": {},
233233
"shebangInjectedAssets": Set {},
234+
"shimsInjectedAssets": Set {},
234235
},
235236
],
236237
},
@@ -474,6 +475,7 @@ exports[`Should compose create Rsbuild config correctly > Merge Rsbuild config i
474475
"shebangChmod": 493,
475476
"shebangEntries": {},
476477
"shebangInjectedAssets": Set {},
478+
"shimsInjectedAssets": Set {},
477479
},
478480
],
479481
},
@@ -695,6 +697,7 @@ exports[`Should compose create Rsbuild config correctly > Merge Rsbuild config i
695697
"shebangChmod": 493,
696698
"shebangEntries": {},
697699
"shebangInjectedAssets": Set {},
700+
"shimsInjectedAssets": Set {},
698701
},
699702
],
700703
},
@@ -851,6 +854,7 @@ exports[`Should compose create Rsbuild config correctly > Merge Rsbuild config i
851854
"shebangChmod": 493,
852855
"shebangEntries": {},
853856
"shebangInjectedAssets": Set {},
857+
"shimsInjectedAssets": Set {},
854858
},
855859
],
856860
},

pnpm-lock.yaml

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"name": "shims-copy-test",
3+
"version": "1.0.0",
4+
"private": true,
5+
"type": "module"
6+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { defineConfig } from '@rslib/core';
2+
import { generateBundleCjsConfig } from 'test-helper';
3+
4+
export default defineConfig({
5+
lib: [
6+
generateBundleCjsConfig({
7+
shims: { esm: { __dirname: true, __filename: true } },
8+
}),
9+
],
10+
output: {
11+
copy: ['./src/a/index.ts'],
12+
},
13+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/user/bin/env node
2+
3+
export default 'ok';
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const squared = (n: number): number => n * n;

tests/integration/shims/index.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import fs from 'node:fs';
12
import path, { join } from 'node:path';
23
import { pathToFileURL } from 'node:url';
34
import vm from 'node:vm';
@@ -119,3 +120,18 @@ describe('CJS shims', () => {
119120
`);
120121
});
121122
});
123+
124+
describe('shims with copy', () => {
125+
test('the CJS shims should not affect files in `output.copy`', async () => {
126+
const fixturePath = join(__dirname, 'copy');
127+
await buildAndGetResults({ fixturePath });
128+
const copiedFile = path.resolve(fixturePath, 'dist/cjs/index.ts');
129+
const copiedContent = fs.readFileSync(copiedFile, 'utf-8');
130+
expect(copiedContent).toMatchInlineSnapshot(`
131+
"#!/user/bin/env node
132+
133+
export default 'ok';
134+
"
135+
`);
136+
});
137+
});

0 commit comments

Comments
 (0)