Skip to content
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

fix: using node:fs would lead to an error like 'missing /node:fs.js' #6431

Merged
merged 9 commits into from
Oct 24, 2024
5 changes: 5 additions & 0 deletions .changeset/quiet-mirrors-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modern-js/plugin-module-node-polyfill': patch
---

fix: using node:fs with node polyfill will lead to an error
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,6 @@ export default {
};
```

#### Clean up cert cache

The certificate created by devcert is saved in `~/Library/Application\ Support/devcert`. You may do some cleanup if needed.
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,6 @@ export default {
};
```

#### 清理证书缓存

devcert 默认会将生成的证书缓存在 `~/Library/Application\ Support/devcert` ,你可以按需清理。
11 changes: 5 additions & 6 deletions packages/module/plugin-module-node-polyfill/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import type {
ICompiler,
ModuleTools,
} from '@modern-js/module-tools';
import { addNodePrefix, addResolveFallback, excludeObjectKeys } from './utils';
import { excludeObjectKeys, fillResolveAndFallback } from './utils';

export interface NodePolyfillPluginOptions {
// like https://github.com/Richienb/node-polyfill-webpack-plugin#excludealiases
excludes?: string[];
// override built-in node polyfill config, such as `fs`.
overrides?: Partial<Record<keyof typeof modules, string>>;
overrides?: Partial<Record<keyof typeof defualtModules, string>>;
}

let modules = {
const defualtModules = {
assert: require.resolve('assert/'),
buffer: require.resolve('buffer/'),
child_process: null,
Expand Down Expand Up @@ -60,11 +60,10 @@ let modules = {
export const getNodePolyfillHook = (
polyfillOption: NodePolyfillPluginOptions = {},
) => {
const nodeModules = addNodePrefix(modules);
modules = Object.assign(modules, nodeModules);
const modules = { ...defualtModules };
const polyfillModules = {
...excludeObjectKeys(
addResolveFallback(modules, polyfillOption.overrides),
fillResolveAndFallback(modules, polyfillOption.overrides),
polyfillOption.excludes ?? [],
),
};
Expand Down
24 changes: 8 additions & 16 deletions packages/module/plugin-module-node-polyfill/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,22 @@ export function excludeObjectKeys(
return filterObject(object, key => !keys.includes(key));
}

export function addResolveFallback(
export function fillResolveAndFallback(
object: Record<string, string | null>,
overrides: Record<string, string> = {},
) {
const keys = Object.keys(object);
const newObject: Record<string, string> = {};
for (const key of keys) {
let resultModule: string;
if (object[key] === null) {
newObject[key] = path.join(__dirname, `./mock/${key}.js`);
resultModule = path.join(__dirname, `./mock/${key}.js`);
} else {
newObject[key] = object[key] as string;
resultModule = object[key] as string;
}
newObject[key] = resultModule;
if (!key.startsWith('_')) {
newObject[`node:${key}`] = resultModule;
}
}

Expand All @@ -42,16 +47,3 @@ export function addResolveFallback(

return newObject;
}

export function addNodePrefix(
modules: Record<string, string | null>,
): Record<string, string | null> {
return Object.fromEntries(
Object.entries(modules).map(([key, value]) => {
if (!key.startsWith('_')) {
return [`node:${key}`, value];
}
return [key, value];
}),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,10 @@ import { modulePluginNodePolyfill } from '@modern-js/plugin-module-node-polyfill

export default defineConfig({
plugins: [modulePluginNodePolyfill()],
buildConfig: {
input: {
index: './src/index.js',
another_entry: './src/another_entry.js',
},
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,15 @@ describe('plugin-node-polyfill', () => {
'utf8',
);
expect(content).toContain('init_globals()');
expect(content).toContain('__toESM(require_browser2())');
expect(content).toContain('__toESM(require_path_browserify())');
expect(content).toContain('__toESM(require_browser2())');

const anotherContent = fs.readFileSync(
path.resolve(__dirname, 'dist/another_entry.js'),
'utf8',
);
expect(anotherContent).toContain('init_globals()');
expect(anotherContent).toContain('__toESM(require_path_browserify())');
expect(anotherContent).toContain('os-browserify/browser');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'os';

console.log(fs);
console.log(path);
console.log(os);
export const value = Buffer.from('value');
8 changes: 6 additions & 2 deletions tests/integration/module/plugins/node-polyfill/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import os from 'node:os';
import path from 'path';
import fs from 'fs'; // should be replaced by modern.js mock
import os from 'node:os'; // should be replaced by os-browserify
import path from 'path'; // should be replaced by path-browserify

console.log(fs);
console.log(path);
console.log(os);
export const value = Buffer.from('value');
Loading