Skip to content

feat: support import.meta.url shim for CJS #216

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
Sep 18, 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
6 changes: 6 additions & 0 deletions e2e/cases/shims/cjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "shims-cjs-test",
"version": "1.0.0",
"private": true,
"type": "module"
}
14 changes: 14 additions & 0 deletions e2e/cases/shims/cjs/rslib.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { generateBundleCjsConfig } from '@e2e/helper';
import { defineConfig } from '@rslib/core';

export default defineConfig({
lib: [generateBundleCjsConfig()],
output: {
target: 'node',
},
source: {
entry: {
index: './src/index.ts',
},
},
});
3 changes: 3 additions & 0 deletions e2e/cases/shims/cjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const foo = () => {
console.log(import.meta.url);
};
13 changes: 12 additions & 1 deletion e2e/cases/shims/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,15 @@ test('shims for __dirname and __filename in ESM', async () => {
}
});

test.todo('shims for import.meta.url in CJS', 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() {
'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);
}
});
16 changes: 16 additions & 0 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
DEFAULT_EXTENSIONS,
SWC_HELPERS,
} from './constant';
import { pluginCjsShim } from './plugins/cjsShim';
import type {
AutoExternal,
BannerAndFooter,
Expand Down Expand Up @@ -456,8 +457,16 @@ const composeFormatConfig = (format: Format): RsbuildConfig => {
};
case 'cjs':
return {
plugins: [pluginCjsShim()],
tools: {
rspack: {
module: {
parser: {
javascript: {
importMeta: false,
},
},
},
output: {
iife: false,
chunkFormat: 'commonjs',
Expand All @@ -472,6 +481,13 @@ const composeFormatConfig = (format: Format): RsbuildConfig => {
return {
tools: {
rspack: {
module: {
parser: {
javascript: {
importMeta: false,
},
},
},
output: {
library: {
type: 'umd',
Expand Down
41 changes: 41 additions & 0 deletions packages/core/src/plugins/cjsShim.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { type RsbuildPlugin, rspack } from '@rsbuild/core';

const importMetaUrlShim = `var __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
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`.
// - Inject `importMetaUrl` to the end of the module (can't inject at the beginning because of `"use strict";`).
// This is a short-term solution, and we hope to provide built-in polyfills like `node.__filename` on Rspack side.
export const pluginCjsShim = (): RsbuildPlugin => ({
name: 'rsbuild-plugin-cjs-shim',

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

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)$/,
}),
);
});
},
});
20 changes: 20 additions & 0 deletions packages/core/tests/__snapshots__/config.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ exports[`Should compose create Rsbuild config correctly > Merge Rsbuild config 1
"not dead",
],
},
"plugins": [
{
"name": "rsbuild-plugin-cjs-shim",
"setup": [Function],
},
],
"source": {
"alias": {
"bar": "bar/cjs",
Expand Down Expand Up @@ -243,6 +249,13 @@ exports[`Should compose create Rsbuild config correctly > Merge Rsbuild config 1
},
{
"externalsType": "commonjs",
"module": {
"parser": {
"javascript": {
"importMeta": false,
},
},
},
"output": {
"chunkFormat": "commonjs",
"iife": false,
Expand Down Expand Up @@ -373,6 +386,13 @@ exports[`Should compose create Rsbuild config correctly > Merge Rsbuild config 1
},
{
"externalsType": "umd",
"module": {
"parser": {
"javascript": {
"importMeta": false,
},
},
},
"output": {
"library": {
"type": "umd",
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading