Newbie to Electron and Vite here. I'm betting this is a simple question that I'm missing obvious on.
I'm trying to run a background process through using a utilityProcess. The first parameter in the fork method is the file path to the utility script.
Here's my file structure:
src
├── index.html
├── main.js
├── preload.js
├── renderer.js
├── test.js (utility process file)
Here's my main.js file content:
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
});
// and load the index.html of the app.
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
}
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.postMessage({ message: 'test' }, [port1])
// Open the DevTools.
mainWindow.webContents.openDevTools();
};
I know the issue is me using path.join(__dirname, 'test.js') since this works if I use Electron without webpack or Vite. I'm trying to figure out to resolve the test.js file correctly through Vite so I can execute that file. I gave explicit URL imports a shot to with no luck.
Vite does support this, but you need to import the child process using the ?modulePath suffix to prevent the child process code from being bundled into index.js.
See https://electron-vite.org/guide/dev#utility-process-and-child-process for more information, including the following example:
// main.ts
import { utilityProcess, MessageChannelMain } from 'electron'
import forkPath from './fork?modulePath'
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(forkPath)
child.postMessage({ message: 'hello' }, [port1])
port2.on('message', (e) => {
console.log(`Message from child: ${e.data}`)
})
port2.start()
port2.postMessage('hello')
// fork.ts
process.parentPort.on('message', (e) => {
const [port] = e.ports
port.on('message', (e) => {
console.log(`Message from parent: ${e.data}`)
})
port.start()
port.postMessage('hello')
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With