Press "Enter" to skip to content

How to use child_process.fork() in electron-vue (Electron with webpack)

Process Interaction

+----------+                +---------+               +--------+
| Renderer |  -- request -> | Main    | -- request -> | Forked |
| process  |  <- response - | process | <- response - | worker |
+----------+                +---------+               +--------+

Project Structure

I try to keep the original project structure given by electron-vue. Only worker.js is added:

/
|-.electron-vue/
  |-webpack.main.config.js
|-dist/
|-src/
  |-main/
  | |-index.js
  |-renderer/
  |-worker/
    |-worker.js

Configuring webpack

webpack.main.config.js

const CopyWebpackPlugin = require('copy-webpack-plugin')

if (process.env.NODE_ENV === 'production') {
  mainConfig.plugins.push(
    new CopyWebpackPlugin([
      {
        from: path.join(__dirname, '../src/worker'),
        to: path.join(__dirname, '../dist/electron/worker'),
        ignore: ['.*']
      }
    ])
  )
}

Configuring electron-builder

child_process.fork() cannot be used with a script packed in app.asar. Hence, we need to ensure that a worker script is not packed in app.asar:

"build": {
  "win": {
    "asarUnpack": [
      "dist/electron/worker/worker.js"
    ]
  }
}

If you need to build a Mac/Linux app, put asarUnpack in the corresponding platform configuration

Worker by using child_process.fork()

index.js

import { fork } from 'child_process'

const workerPath = process.env.NODE_ENV === 'development'
  ? 'worker/worker.js'
  : join(__dirname, 'worker/worker.js')
const worker = fork(workerPath)

The main process shall forward request from the renderer process to the worker:

ipcMain.on('event-name', (event, data) => {
  worker.send({
    event: 'event-name',
    data
})

To forward response from the worker to the renderer process:

worker.on('message', (msg) => {
  const {event, data} = msg
  mainWindow.webContents.send(event, data)
})

worker.js

process.on('message', (msg) => {
  const {event, data} = msg
  // Do something with event name and data
})