Vite 2/Vue 3 项目中导入 Electron 及 Node 原生模块报错如何解决
错误原因
Vite 默认将构建目标设定为浏览器环境,所有 Node.js 内置模块(path/fs 等)、Electron 专属模块都会在编译阶段被替换为浏览器适配垫片,你拿到的 path 模块是仅支持 URL 路径处理的浏览器版本,没有 Node.js 专属的 join 等文件路径操作方法,因此会出现 undefined 报错。Electron 模块本身依赖 Node 环境加载,直接在 Vite 编译的前端代码中导入也会触发加载异常。
解决方案
方案1:通过预加载脚本暴露能力(官方推荐,安全性最高)
Electron 官方不推荐在渲染进程直接开启 nodeIntegration,你可以将需要用到的 Node/Electron 能力全部在 preload 脚本中封装后暴露给渲染进程,无需修改 Vite 配置。
- 编辑
electron.preload.js:
const { contextBridge } = require('electron') const path = require('path') const fs = require('fs-extra') // 如果你保持了contextIsolation: false,可以直接挂载到window对象,否则用contextBridge contextBridge.exposeInMainWorld('electronAPI', { pathJoin: (...args) => path.join(...args), readFile: (filePath) => fs.readFile(filePath, 'utf-8'), writeFile: (filePath, content) => fs.writeFile(filePath, content), // 其他你需要使用的方法都可以在这里封装暴露 })
- 在 Vue 业务代码中直接调用挂载的方法,无需导入任何 Node/Electron 模块:
console.log(window.electronAPI.pathJoin('a', 'b', 'c'))
方案2:修改Vite配置支持直接导入Node模块
如果你坚持要在渲染进程直接导入相关模块,可以修改 Vite 配置将这些模块标记为外部依赖,跳过 Vite 的编译,直接从 Node 环境加载:
编辑 vite.config.js:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], // 构建配置 build: { rollupOptions: { // 将Node内置模块、Electron相关模块标记为外部依赖 external: ['electron', 'path', 'fs', 'fs-extra'], output: { // 配置外部模块的加载方式为CommonJS require globals: { electron: 'require("electron")', path: 'require("path")', 'fs-extra': 'require("fs-extra")' } } } }, // 开发阶段依赖预构建排除相关模块 optimizeDeps: { exclude: ['electron', 'path', 'fs-extra'] }, // 注入Node全局变量 define: { __dirname: '__dirname', __filename: '__filename' } })
修改配置后即可在业务代码中直接导入对应模块使用。
内容的提问来源于stack exchange,提问作者Solsiden
相关产品推荐
相关产品推荐

