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

Electron Forge+TS项目集成node:test的ESM兼容问题

Electron Forge + Webpack + TypeScript 集成 node:test 的冲突问题

问题概述

基于 Electron Forge 的 Webpack+TypeScript 模板开发应用,尝试集成 node:test 实现单元测试时遇到冲突:只有在 package.json 中添加 "type": "module" 时测试可正常运行,但此时执行 npm run start 启动应用,Electron Forge 加载 forge.config.ts 会报错,提示无法用 require() 加载 ES 模块。修改 tsconfig.json 的 module 配置、重命名测试文件为 .mts 等方法均未彻底解决问题,寻求可行解决方案。

相关报错与配置

测试执行报错(未添加 "type": "module" 时)

> {myproject}@0.0.1 test
> glob -c  "node --loader tsx --no-warnings --test" "tests/**/*.ts"

{myrepo}\tests\server-log\parse-lines.ts:1
  import assert from 'assert/strict';
  ^^^^^^

  SyntaxError: Cannot use import statement outside a module

应用启动报错(添加 "type": "module" 时)

✖ Loading configuration                                                                                                                              
  › Must use import to load ES Module: {myrepo}\forge.config.ts                   
  require() of ES…                                                                                                                                    
◼ Preparing native dependencies                                                                                                                      
◼ Running generateAssets hook                                                                                                                        

An unhandled rejection has occurred inside Forge:
Error: Must use import to load ES Module: {myrepo}\forge.config.ts
require() of ES modules is not supported.
require() of {myrepo}\forge.config.ts from {myrepo}\node_modules\@electron-forge\core\dist\util\forge-config.js is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
Instead change the requiring code to use import(), or remove "type": "module" from {myrepo}\package.json.

当前 tsconfig.json 配置

{
  "compilerOptions": {
    "target": "ES6",
    "allowJs": true,
    "module": "commonjs",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "noImplicitAny": true,
    "sourceMap": true,
    "baseUrl": ".",
    "outDir": "dist",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "src/**/*.ext",
  ]
}

测试脚本(package.json 中)

"test": "glob -c  \"node --loader tsx --no-warnings --test\" \"tests/**/*.ts\"",

已尝试的方案

  • 将测试文件改为 .mts 格式后,导入待测试的 .ts 文件时出现导出相关报错,修改导出方式仍未解决
  • 尝试为 tsx 单独配置 tsconfig、在子目录设置 package.json 指定 type 为 module,均未成功

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:56:14