Angular-Electron-NX升级后require()加载ES模块报错求助
解决Angular 16 + NX 16 + Electron 26升级后的ES模块加载报错问题
问题本质
升级到Angular 16、NX 16、Electron 26并使用nx-electron 16.0.0-beta.1后,运行Electron服务时出现Error [ERR_REQUIRE_ESM],核心原因是构建生成的main.js中存在不符合ES模块规范的require()语句,而@angular/core已转为ES模块(.mjs格式),Node.js的require()无法加载这类模块,必须改用动态import()。
解决方案
1. 调整nx-electron配置,强制输出ES模块
nx-electron 16.0.0-beta.1作为测试版本,ES模块兼容存在缺陷,可通过配置强制开启ES模块输出:
- 修改项目
project.json中electron的构建目标配置,添加format: "esm":{ "targets": { "build": { "executor": "nx-electron:build", "options": { "format": "esm", "outputPath": "dist/apps/electron", "main": "apps/electron/src/main.ts", "tsConfig": "apps/electron/tsconfig.app.json" } } } } - 同步更新Electron项目的
tsconfig.app.json:{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "node16", "esModuleInterop": true } } - 在Electron项目根目录的
package.json中添加"type": "module",声明项目使用ES模块规范。
2. 同步调整Angular项目的ES模块输出配置
确保Angular项目的构建产物也是ES模块,避免跨模块规范冲突:
- 修改Angular项目的
tsconfig.json:{ "compilerOptions": { "module": "ES2022", "moduleResolution": "node16" } } - 在Angular项目的
project.json构建配置中开启outputEsModule:{ "targets": { "build": { "executor": "@angular-devkit/build-angular:browser", "options": { "outputEsModule": true } } } }
3. 临时修复:注入脚本替换非法require语句
如果上述配置无法生效,可以通过post-build脚本批量替换生成的main.js中的require()语句:
- 新建
scripts/post-build-fix.js脚本:const fs = require('fs'); const path = require('path'); const mainJsPath = path.join(__dirname, '../dist/apps/electron/main.js'); let content = fs.readFileSync(mainJsPath, 'utf8'); // 替换所有@angular相关的require为动态import content = content.replace(/require\('@angular\/[^']+'\)/g, match => { const moduleName = match.match(/'([^']+)'/)[1]; return `import('${moduleName}')`; }); fs.writeFileSync(mainJsPath, content); - 在项目根目录
package.json中添加post-build钩子:
确保nx-electron完成构建后自动执行该脚本。{ "scripts": { "post-electron-build": "node scripts/post-build-fix.js" } }
关于nx-electron 16.0.0-beta.1的说明
该版本处于beta测试阶段,ES模块兼容问题属于已知的测试版缺陷。建议:
- 关注nx-electron官方发布日志,等待正式版修复;
- 若需临时规避,可降级到nx-electron 15.x版本(需配合NX 15),待正式版推出后再升级。
内容的提问来源于stack exchange,提问作者NRade
相关产品推荐
相关产品推荐

