Webpack打包Fastify项目运行bundle.mjs报require未定义错误求助
解决ES模块bundle中require未定义的问题(Fastify+Webpack+TypeScript)
我用Node.js的Fastify框架(TypeScript、ES语法)开发应用,通过Webpack完成打包与TypeScript编译。打包成功,但运行生成的bundle.mjs时出现以下错误:
ReferenceError: require is not defined in ES module scope, you can use import instead at Object.events (file:///home/myzader/vc-app/backend/dist/bundle.mjs:601068:1) at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41) at ./node_modules/pino/lib/proto.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:612505:26) at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41) at ./node_modules/pino/pino.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613549:15) at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41) at ./node_modules/fastify/lib/logger.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:607600:14) at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41) at ./node_modules/fastify/lib/reply.js (file:///home/myzader/vc-app/backend/dist/bundle.mjs:608101:21) at __webpack_require__ (file:///home/myzader/vc-app/backend/dist/bundle.mjs:613956:41)
我试过调整Webpack配置,把部分依赖加入externals数组后,对应的包不再报错,但其他依赖又出现相同问题。当前Webpack配置如下:
const config = { mode: 'development', devtool: 'source-map', entry: './app.ts', target: 'node', resolve: { extensions: ['.ts', '.js', '.mjs'], }, output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.mjs', // Change the extension to .mjs library: { type: 'module' // Change the library type to 'module' }, chunkFormat: 'module' // Change the chunk format to 'module' }, experiments: { outputModule: true }, externals: [ nodeExternals({ allowlist: ['canvas', 'fastify', 'avvio', 'fastq', 'reusify', '@fastify/error', 'process-warning', 'abstract-logging', 'pino', 'pino-std-serializers', 'fast-redact', 'quick-format-unescaped'] }) ], module: { rules: [{ test: /\.(ts|js)$/, // Handle both .ts and .js files use: 'ts-loader', exclude: /node_modules/ }, { test: /.node$/, // Apply this rule to files ending in .node loader: 'node-loader', // Use the node-loader for all .node files }, ], }, stats: { errorDetails: true, // Display details of errors colors: true, // Output in colored format, useful in console modules: true, // Display modules information reasons: true, // Display the reason about why modules are included warnings: true, // Display warnings }, plugins: [ new webpack.ContextReplacementPlugin( /awilix/, // The module that includes dynamic requires (data) => { delete data.dependencies[0].critical; // Remove the critical flag from these dependencies return data; } ), ], };
解决方案
1. 修正externals配置,排除所有node_modules依赖
你当前的allowlist把大量依赖强行打包进了bundle,而这些依赖内部用的是CommonJS语法,在ES模块环境里运行就会触发require未定义的错误。直接清空allowlist,让nodeExternals排除所有node_modules包:
externals: [nodeExternals()]
这样Webpack不会把第三方依赖打包进bundle,而是保留ES模块的import引用,运行时由Node.js自行加载这些依赖,自动处理它们的模块格式。
2. 确保TypeScript配置输出ES模块
检查tsconfig.json,保证编译后的代码是ES模块:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "target": "ES2020", "outDir": "./dist", "esModuleInterop": true } }
3. 确认package.json的模块类型
项目根目录的package.json必须设置:
{ "type": "module" }
让Node.js默认把所有.js/.mjs文件当作ES模块处理,避免模块格式冲突。
4. 可选:调整Webpack解析规则(如需打包部分依赖)
如果必须打包某些依赖,添加resolve.mainFields优先加载ES模块入口:
resolve: { extensions: ['.ts', '.js', '.mjs'], mainFields: ['module', 'main'] }
不过这种方式可能引入更多兼容性问题,优先推荐排除所有node_modules的方案。
核心问题是你将使用CommonJS语法的第三方依赖打包进了ES模块bundle,导致运行时环境不兼容。通过排除node_modules依赖,让Node.js自行处理外部模块加载,就能彻底解决这类问题。
内容的提问来源于stack exchange,提问作者Toto
相关产品推荐
相关产品推荐

