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

Electron+React+Vite集成Serialport时__dirname未定义错误求助

Electron + Vite 集成 serialport 报错 __dirname is not defined 的原因与解决方法

问题原因

  • Vite 默认采用 ES 模块(ESM)规范处理项目代码,而 __dirname 是 CommonJS(CJS)规范特有的内置变量,ESM 环境中不存在该变量。
  • 未使用 Vite 时,Electron 主进程默认以 CJS 模式运行,serialport 内部依赖的 __dirname 能正常识别;但 Vite 会将主进程代码转译为 ESM 格式,导致 serialport 调用 __dirname 时触发报错。

解决方案

方案1:手动在主进程中定义 __dirname

在 Electron 主进程的入口文件开头添加以下代码,手动模拟 CJS 环境下的 __dirname:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

方案2:配置 Vite 让主进程以 CJS 格式构建

修改项目根目录下的 vite.config.ts,指定 Electron 主进程的输出格式为 CJS:

import { defineConfig } from 'vite';
import electron from 'vite-plugin-electron';

export default defineConfig({
  plugins: [
    electron({
      main: {
        entry: 'electron/main.ts', // 替换为你的主进程入口路径
        formats: ['cjs'],
      },
    }),
  ],
});

方案3:调整 package.json 的模块类型配置

如果你的 package.json 中存在 "type": "module",会让整个项目默认启用 ESM。可以:

  • 将主进程相关文件的后缀改为 .cjs,让 Node.js 以 CJS 模式处理这些文件
  • 若项目不强制要求 ESM,可直接移除 package.json 中的 "type": "module" 字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:32:06