Electron Forge项目适配ESM遇配置冲突,求解决方案
Electron Forge项目适配ESM的配置问题
需求背景
- 项目必须适配ESM,因为依赖的第三方库仅提供ESM导出版本,且无法使用旧版库
- 拒绝使用hack手段、分支处理或特殊导入方式来让ESM库在CommonJS环境运行
遇到的问题
Electron自v28版本起已支持ESM,Electron Forge作为官方打包工具,但项目中的forge.config.ts文件无法兼容ESM导入,报错信息如下:
An unhandled rejection has occurred inside Forge:
Error: Must use import to load ES Module: ~\forge.config.ts
require() of ES modules is not supported.
require() of ~\forge.config.ts from ~\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 ~\package.json.
两种配置尝试的结果
- 配置1:
package.json设置type: "module",同时tsconfig.json配置如下:
代码逻辑可正常运行,但无法启动Forge应用"module": "node16", "moduleResolution": "node16", "moduleDetection": "force" - 配置2:
tsconfig.json配置如下:
可正常启动Forge应用,甚至能导入nanoid等ESM包,但electron-store这类包的类型无法被正确识别"module": "commonjs", "moduleResolution": "node"
疑问
当前Electron开发的ESM适配现状如何?是否存在完美的配置方案?或是我遗漏了某些关键步骤?
内容的提问来源于stack exchange,提问作者danikaze
相关产品推荐
相关产品推荐

