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

Electron+TypeScript项目跨类调用与模块导入报错求助

解决TypeScript+Electron项目中类导入导出的模块报错问题

核心问题原因

你的项目存在模块系统冲突:package.json中设置了"type": "module"(ES模块),但TypeScript配置的module是CommonJS,且直接运行了未编译的TypeScript源文件,导致Electron/Node.js无法正确解析模块语法。

针对第一种场景的分步解决方案

1. 修正package.json配置

  • 删除"type": "module"字段(Node.js默认使用CommonJS模块系统,和你的tsconfig配置匹配)
  • 将main字段改为编译后的入口文件路径:"main": "dist/app.js"(对应tsconfig中outDir: "dist"的配置)

修改后的package.json关键部分:

{
  "name": "pupil",
  "version": "1.0.0",
  "description": "",
  "main": "dist/app.js",
  "scripts": {
    "test": "jest",
    "build": "tsc -p tsconfig.json",
    "start": "npm run build && electron ."
  },
  // ...其他配置不变
}

2. 统一TypeScript文件的导入导出语法

所有.ts文件使用ES模块语法(TypeScript编译后会自动转为CommonJS):

  • app.ts(入口文件):
/** 
 * Entry point of program
 */
import { MainPage } from './ui/mainpage';

let menu = new MainPage();
menu.startApplication();
  • ui/mainpage.ts:
import { app, BrowserWindow } from 'electron';

export class MainPage {
    /**
     * Creates the main menu, using value from constructor
     */
    startApplication() {
        let mainWindow;

        app.on('ready', () => {
            mainWindow = new BrowserWindow({
                // 你的窗口配置字段
            });
            mainWindow.loadURL(`file://${__dirname}/ui/views/index.html`);
        });
    }
}

3. 保持tsconfig.json配置不变

你的现有tsconfig配置已经符合需求,确保编译后输出CommonJS模块到dist目录:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "outDir": "dist",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

4. 重新编译并运行

执行以下命令:

npm run build
npm start

错误原因详解

  • unexpected token 'export':直接用require加载未编译的.ts文件,Node.js将其当作JS文件解析,而export是ES模块语法,和CommonJS的require不兼容,且未经过TypeScript转译导致语法报错。
  • Cannot find module './logic/mainpage':模块路径未对应编译后的文件,且未编译的.ts文件无法被Node.js正确识别为模块。
  • Cannot use import statement outside a module:package.json设了type: module,但Electron默认用CommonJS加载入口文件,同时直接运行未编译的.ts源文件,导致模块系统冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:09:57