diff --git a/e2e/cases/shims/cjs/rslib.config.ts b/e2e/cases/shims/cjs/rslib.config.ts index bf6482cd4..23f9d4e2a 100644 --- a/e2e/cases/shims/cjs/rslib.config.ts +++ b/e2e/cases/shims/cjs/rslib.config.ts @@ -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', }, diff --git a/e2e/cases/shims/index.test.ts b/e2e/cases/shims/index.test.ts index 0c6a0a42e..3f290a2ab 100644 --- a/e2e/cases/shims/index.test.ts +++ b/e2e/cases/shims/index.test.ts @@ -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'); @@ -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 }; + " + `); + }); }); diff --git a/packages/core/src/plugins/cjsShim.ts b/packages/core/src/plugins/cjsShim.ts index 76674a50f..9311bfef7 100644 --- a/packages/core/src/plugins/cjsShim.ts +++ b/packages/core/src/plugins/cjsShim.ts @@ -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__',