Webpack5编译Node服务端代码仍生成require,如何输出ESM?
问题
我配置Webpack 5编译Node服务端代码,期望输出纯ESM语法而非CommonJS,相关配置如下:
Webpack 核心配置
const config: Configuration = merge(common, overrides, { name: 'server', target: 'node', experiments: { outputModule: true, topLevelAwait: true, }, output: { path: paths.appBuild, filename: options.filename, publicPath, library: { type: 'module', }, chunkFormat: 'module', environment: { const: true, destructuring: true, forOf: true, module: true, templateLiteral: true, }, },
配套配置
- package.json 已设置
"type": "module" - tsconfig.json compilerOptions 片段:
"compilerOptions": { "baseUrl": ".", "target": "ESNext", "module": "ESNext",
但编译输出仍出现CommonJS的require语句:
const svg_namespaceObject = require("@cutting/svg");
需要解决该问题,确保输出为纯ESM语法。
解决方案
1. 强制转换第三方CommonJS依赖为ESM
问题中的@cutting/svg大概率是CommonJS模块,Webpack默认会保留其require语法。可通过以下配置强制转换:
在Webpack配置的module.rules中添加规则:
module: { rules: [ { test: /node_modules\/@cutting\/svg/, type: 'javascript/esm', }, ], },
同时调整resolve配置,优先识别ESM后缀:
resolve: { extensions: ['.mjs', '.js', '.ts', '.tsx'], mainFields: ['module', 'main'], // 优先加载依赖的ESM入口 },
2. 优化Webpack的CommonJS解析规则
在Webpack配置中添加parser配置,强制处理CommonJS调用:
module: { parser: { javascript: { commonjsRequireCalls: true, commonjsMagicComments: true, }, }, },
3. 完善TypeScript配置
确保tsconfig.json补充以下关键配置,避免TypeScript输出CommonJS语法:
"compilerOptions": { "moduleResolution": "node16", // 匹配Node.js ESM解析逻辑 "esModuleInterop": true, "allowSyntheticDefaultImports": true, "module": "ESNext", "target": "ESNext", "strict": true }
4. 指定Node版本目标
将Webpack的target明确设置为支持ESM的Node版本(如node18+),让Webpack针对性优化:
target: 'node18',
内容的提问来源于stack exchange,提问作者dagda1
相关产品推荐
相关产品推荐

