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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:51:01