Using the webpack working bootloader with nuxt.js

I try to use Web Worker as part of nuxt.js, but keep getting the link error. ReferenceError: Worker is not defined.

I installed worker-loader 1.1.1 via npm and added the following rule to my nuxt.config.js:

module.exports = {
  build: {
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
      // Web Worker support
      config.module.rules.push({
        test: /\.worker\.js$/,
        use: { loader: 'worker-loader' },
        exclude: /(node_modules)/
      })
    }
  }
}

If I create an assembly through nuxt buildit looks like a web worker file has been created.

Asset                           Size                      
2a202b9d805e69831a05.worker.js  632 bytes          [emitted]

I import it into the vuex module, like this:

import Worker from '~/assets/js/shared/Loader.worker.js'

console.log(Worker)
const worker = new Worker // <- this line fails!

In the console, I get what looks like a function to create an employee:

ƒ () {
  return new Worker(__webpack_require__.p + "345c16d02e75e9312f73.worker.js");
}

Inside the worker, I have just dummy code to see if it actually works:

const msg = 'world!'

self.addEventListener('message', event => {
  console.log(event.data)
  self.postMessage({ hello: msg })
})

self.postMessage({ hello: 'from web worker' })
+6
source share
2 answers

Let some things be solved first:

  • workers are available only on the client side → no ssr

, no ssr component, ssr

nuxt.config.js :

mode: 'spa',
build: {
  extend(config, { isDev, isClient }) {
    ...
    // Web Worker support
    if (isClient) {
      config.module.rules.push({
        test: /\.worker\.js$/,
        use: { loader: 'worker-loader' },
        exclude: /(node_modules)/
      })
    }
  }
}

npm run build npm run start .

, nuxt : Github Repo

+3

, ( , ) , . , . , / , FaaS, .

, nuxt.config.js? " ". ( , )

extend(config, ctx) {
    /*
    ** Required for HotModuleReloading to work with worker-loader
    */
    config.output.globalObject = 'this'
}
+1

Source: https://habr.com/ru/post/1694562/


All Articles