How fix __dirname not defined when using electron events with Vue? How fix __dirname not defined when using electron events with Vue? vue.js vue.js

How fix __dirname not defined when using electron events with Vue?


To solve this I created a file vue.config.js in project root with content

module.exports = {    pluginOptions: {        electronBuilder: {            nodeIntegration: true        }    }}


There are two processes in electron, the main process and the renderer process. Your Vue component is the renderer process. In order to communicate between these two processes, you need inter-processes communication. So in your case, you'd define a channel perhaps in background.js using ipcMain. You'd write something like:

ipcMain.on("my-custom-channel", (event, args) => handleEvent(event, args));

Then in your Vue component, you'd use the renderer process, ipcRendere, such as:

import { ipcRenderer } from "electron";export default {    methods: {        open() {            ipcRenderer.send('my-custom-channel', "hello from Vue!")        }    }}

Point is: you cannot use app.on for your custom events. app.on handles predefined electron events. Use ipcMain.on instead.

reference: https://www.electronjs.org/docs/api/ipc-main


You can apply the solution described on this postHow to import ipcRenderer in vue.js ? __dirname is not defined

In this way you can call window.ipcRenderer.send(channel, args...) from vue files.

Just make sure you configure preload.js on vue.config.js:

// vue.config.js - project rootmodule.exports = {  pluginOptions: {    electronBuilder: {       preload: 'src/preload.js'  //make sure you have this line added    }  }}

Another solution can be found here https://medium.com/swlh/how-to-safely-set-up-an-electron-app-with-vue-and-webpack-556fb491b83 and it use __static to refer to preload file instead of configure it on vue.config.js. To make it work you can disable preload es-lint warning inside of BrowserWindow constructor:

// eslint-disable-next-line no-undefpreload: path.resolve(__static, 'preload.js')

And make sure you added preload.js file on /public folder