Can't use Worker-Loader with Vuejs and Webpack Can't use Worker-Loader with Vuejs and Webpack vue.js vue.js

Can't use Worker-Loader with Vuejs and Webpack


Being new to Javascript I kept coming back to this issue when trying to use web workers with VueJS. I never managed to make it work with vue-worker or worker-loader.

It is now 2020 and Google has released worker-plugin.

To use it create a module my-worker with two files index.js and worker.js.

index.js creates the module:

const worker = new Worker('./worker.js', { type: 'module' });const send = message => worker.postMessage({  message})export default {  worker,  send}

worker.js contains the logic:

import _ from 'lodash'addEventListener("message", async event => {    let arrayToReverse = event.data.message.array    let reversedArray = _.reverse(arrayToReverse)    // Send the reversed array    postMessage(reversedArray)});

You will also need to update your vue.config.js to use the WorkerPlugin:

const WorkerPlugin = require('worker-plugin')module.exports = {  configureWebpack: {    output: {      globalObject: "this"    },    plugins: [      new WorkerPlugin()    ]  }};

Now you can use you worker in your components:

  1. Import it with import worker from '@/my-worker'.
  2. Setup a listener in the mounted() lifecycle hook with worker.worker.onmessage = event => { // do something when receiving postMessage }
  3. Start the worker with worker.send(payload).

I set up a starter code on github. I still haven't managed to make HMR work though...


This works for me (note the first line):

config.module.rule('js').exclude.add(/\.worker\.js$/)config.module  .rule('worker-loader')  .test(/\.worker\.js$/)  .use('worker-loader')  .loader('worker-loader')

The first line excludes worker.js files, so two loaders wouldn't fight over the same js file