vue添加Electron在渲染进程调用ipc报错:__dirname is not defined
错误详情使用vue创建项目并添加vue-cli-plugin-electron-builder插件后在渲染进程中调用ipc与主进程通讯报错:__dirname is not defined错误原因As of v2.0 of VCPEB, Electron nodeIntegration is disabled by default. This blocks all node APIs such a
错误详情
使用vue创建项目并添加vue-cli-plugin-electron-builder插件后在渲染进程中调用ipc与主进程通讯报错:__dirname is not defined
错误原因
As of v2.0 of VCPEB, Electron nodeIntegration is disabled by default. This blocks all node APIs such as require. This reduces security risks, and is a recommended best practice by the Electron team. If you need to use native modules such as fs or sqlite in the renderer process, you can enable nodeIntegration in vue.config.js:
简单来说就是默认是不允许调用node的原生插件,如果需要调用的话需要去将主进程main.js文件中的 createWindow() 方法中的BrowserWindow>webPreferences>nodeIntegration设置为true,既下图位置

并且按照文档中的描述如果只是需要调用ipc进行通讯时不需要进行上述操作,只需要将
import { ipcRenderer } from 'electron'
window.ipcRenderer = ipcRenderer
加入预执行文件中即可
IPC Without Node Integration
You can still use IPC without nodeIntegration. Just create a preload script with the following code:
因此我可以直接新建预执行文件,并将上述代码加入其中并在vue设置文件中进行设置即可
首先在src目录下新建preload.js文件,内容为
import { ipcRenderer } from 'electron'
window.ipcRenderer = ipcRenderer
再在package.json同级目录新建vue.config.js文件,内容为
module.exports = {
pluginOptions: {
electronBuilder: {
preload: 'src/preload.js',
}
}
}
之后渲染进程中使用 window.ipcRenderer调用即可
大致思路其实就是既然渲染进程默认不支持调用,那就在预执行中获取对象,然后存到window对象中,需要用的时候从window调用就好了
官方文档:https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration
更多推荐



所有评论(0)