Electron+TypeScript渲染进程模块导入报错,预加载脚本冲突求助
Electron + TypeScript 跨文件导入兼容解决方案
问题核心
主进程、预加载脚本运行在Node.js环境,天然兼容CommonJS模块;但渲染进程运行在浏览器环境,直接引入CommonJS编译的代码会因缺少exports/require报错。统一修改tsconfig的module字段会顾此失彼,因此需要为不同进程配置独立的编译规则。
具体实现步骤
1. 拆分TypeScript配置文件
创建3个配置文件,分别适配不同运行环境:
根目录 tsconfig.json(基础公共配置)
{ "compilerOptions": { "target": "ES2020", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist", "rootDir": "./src" }, "exclude": ["node_modules"] }
tsconfig.main.json(主进程、预加载脚本专用,CommonJS模块)
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "CommonJS", "moduleResolution": "Node" }, "include": ["src/main.ts", "src/preload.ts"] }
tsconfig.renderer.json(渲染进程专用,ES模块)
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "ESNext", "moduleResolution": "Bundler", "allowImportingTsExtensions": false }, "include": ["src/renderer.ts", "src/stuff.ts"] }
2. 修改编译脚本
在package.json中添加分进程编译的命令,确保各进程代码按对应规则编译:
{ "scripts": { "build:main": "tsc -p tsconfig.main.json", "build:renderer": "tsc -p tsconfig.renderer.json", "build": "npm run build:main && npm run build:renderer", "start": "npm run build && electron ." } }
3. 调整渲染脚本引入方式
在index.html中给渲染脚本添加type="module"属性,告知浏览器这是ES模块:
<html> ... <script src="./dist/renderer.js" type="module"></script> </html>
4. 确认Electron主进程配置
确保main.ts中预加载脚本路径正确,且Web偏好配置符合安全要求:
import { app, BrowserWindow } from 'electron'; import path from 'path'; function createWindow() { const mainWindow = new BrowserWindow({ webPreferences: { contextIsolation: true, preload: path.join(__dirname, 'preload.js') } }); mainWindow.loadFile('index.html'); } app.whenReady().then(createWindow);
原理说明
- 主进程、预加载脚本保持CommonJS编译规则,适配Node.js运行环境,原有逻辑无需修改;
- 渲染进程编译为ES模块,利用浏览器原生支持的模块机制,彻底解决
exports/require未定义的问题; - 通过拆分
tsconfig实现环境隔离,同时兼顾各进程的模块兼容性与运行需求。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

