Electron项目中常见问题汇总
环境依赖
Windows
Windows 环境依赖需要 Visual Studio 和 python Visual Studio 和 python 在安装 node 时会提示安装 window 对应的编译环境勾选安装即可, 或使用脚本安装编译环境,也可以使用 npm 全局安装 windows-build-tools

MacOS
MacOS 环境依赖需要 CommandLineTools (Xcode命令行工具)和 python
electron 更新到 12 后提示 Require is not defined
问题
将项目从 electron 6 升级到 electron 12 后,启动项目渲染进程控制台提示:Require is not defined
解决
项目使用 vue-cli-plugin-electron-builder 搭建,在 vue-cli-plugin-electron-builder 的 github 问题上找到对应答案
问题地址:https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/1349
在 new BrowserWindow 中添加 nodeIntegration 和 contextIsolation 的对应配置
const win = new BrowserWindow({
// ...
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
// ...
},
});
同时修改 vue.config.js
官方说明:https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration
module.exports = {
//...
pluginOptions: {
electronBuilder: {
nodeIntegration: true,
//...
},
},
};
fs.existsSync is not a function
使用 vue-cli-plugin-electron-builder 的项目修改主进程和渲染进程入口文件
修改 vue.config.js
module.exports = {
//...
pluginOptions: {
electronBuilder: {
mainProcessFile: "src/main/index.js",
rendererProcessFile: "src/renderer/index.js",
mainProcessWatch: ["src/main"],
//...
},
},
};
使用 ipcRenderer.sendSync 进程通信后程序卡住(阻塞)问题
使用 ipcRenderer.sendSync 方法进行通信 ,对应的 ipcMain.on 中必须使用 event.returnValue 返回结果
否则 sendSync 会将阻塞整个渲染进程 ,导致程序卡住
官方文档中的警告
⚠️警告:发送同步消息会阻塞整个渲染器进程,直到收到回复,所以只能作为最后的手段使用此方法。使用异步版本要好得多,
invoke().
所以尽量使用 ipcRenderer. send 而非 sendSync 方法, 或者再每个 ipcMain.on 中都添加返回值 event.returnValue ,但是如果操作中报错可能还会导致卡死(阻塞)
建议
如果只需要让主进程执要返行一些操作不需要返回值 就使用 ipcRenderer.send 和 ipcMain.on 组合
如果需要主进程返回值 就使用 ipcRenderer.invoke 和 ipcMain.handle 组合
ipcRenderer.sendSync 在任何情况下都不使用
electron+vue 项目添加 vue-devTools Unrecognized manifest key ‘browser_action‘. Permission ‘contextMenus‘
构建 vue-devtools
手动 clone 项目vue-devtools
git clone https://github.com/vuejs/vue-devtools.git
然后切换到add-remote-devtools分支,默认的是main分支:
git checkout add-remote-devtools
进入vue-devtools根目录:
yarn
# ...
yarn run build
run build
这一步会出现一个特别恶心的 webpack,webpack-cli 互相依赖缺失的问题,提示没有 webpack 模块,然后全局安装 webpack 模块,npm install -g webpack,这时候运行 webpack 指令,会发现缺失 webpack-cli,再次全局安装 webpack-cli,npm install -g webpack-cli,这时候运行 webpack-cli 指令,又莫名其妙的提示缺失 webpack 模块。
原因就是 webpack4.0 的问题,解决办法就是安装指定版本的 webpack:npm install -g webpack@3.6.0,而不是默认,默认会出现 4 以上版本,甚至 5.1 版本或者更高。
但是有的系统如果以前全局安装过 webpack,还是会报这些相互依赖的问题,或者是环境变量导致的 webpack,webpack-cli 安装进了 node 目录,而以前有的 webpack 安装进了 C:\Users\Administrator\AppData\Roaming\npm 这个目录。解决办法就是删除 C:\Users\Administrator\AppData\Roaming\npm 目录下的 webpack。