Skip to content
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
4 changes: 2 additions & 2 deletions e2e/cases/shims/cjs/rslib.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { generateBundleCjsConfig } from '@e2e/helper';
import { generateBundleCjsConfig, generateBundleEsmConfig } from '@e2e/helper';
import { defineConfig } from '@rslib/core';

export default defineConfig({
lib: [generateBundleCjsConfig()],
lib: [generateBundleEsmConfig(), generateBundleCjsConfig()],
output: {
target: 'node',
},
Expand Down
34 changes: 24 additions & 10 deletions e2e/cases/shims/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { join } from 'node:path';
import { buildAndGetResults } from '@e2e/helper';
import { expect, test } from 'vitest';
import { describe, expect, test } from 'vitest';

test('shims for __dirname and __filename in ESM', async () => {
const fixturePath = join(__dirname, 'esm');
Expand All @@ -16,15 +16,29 @@ test('shims for __dirname and __filename in ESM', async () => {
}
});

test('shims for import.meta.url in CJS', async () => {
const fixturePath = join(__dirname, 'cjs');
const { entries } = await buildAndGetResults(fixturePath);
for (const shim of [
`var __rslib_import_meta_url__ = /*#__PURE__*/ function() {
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);
}
'console.log(__rslib_import_meta_url__);',
]) {
expect(entries.cjs).toContain(shim);
}
});

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 };
"
`);
});
});
3 changes: 1 addition & 2 deletions packages/core/src/plugins/cjsShim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ export const pluginCjsShim = (): RsbuildPlugin => ({
name: 'rsbuild-plugin-cjs-shim',

setup(api) {
api.modifyRsbuildConfig((config) => {
config.source ||= {};
api.modifyEnvironmentConfig((config) => {
config.source.define = {
...config.source.define,
'import.meta.url': '__rslib_import_meta_url__',
Expand Down