You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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钩子:
    {
      "scripts": {
        "post-electron-build": "node scripts/post-build-fix.js"
      }
    }
    
    确保nx-electron完成构建后自动执行该脚本。

关于nx-electron 16.0.0-beta.1的说明

该版本处于beta测试阶段,ES模块兼容问题属于已知的测试版缺陷。建议:

  • 关注nx-electron官方发布日志,等待正式版修复;
  • 若需临时规避,可降级到nx-electron 15.x版本(需配合NX 15),待正式版推出后再升级。

内容的提问来源于stack exchange,提问作者NRade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:27:31