简体   繁体   中英

How to use javascript webworker in webpack?

i'm trying to use web workers in my web app but i'm having a hard time. Adding a new entry to the webpack.config.js does not work.

so, I'm trying to use the npm package called worker-loader but there is no proper example on how to use it. All of my attempts to use it has failed. Can you guys please show me a simple example on how to use it.

import Worker from "worker-loader!./Worker.js";
const myworker = new Worker();
myworker.postMessage(songs);
myworker.onmessage = function(Data) {
//do something
}

my webpack.config.js file is like this with

 entry: __dirname + "/js/index.js",
 output: {
 path: __dirname + "/dist",
 filename: "bundle.js"
 },  
{
  module: {
    rules: [
     {
    test: /\.worker\.js$/,
    use: { loader: 'worker-loader' }
  }
]
}
}

My server tells me the following:

"GET /279b1e1fcb403131377a.worker.js HTTP/1.1" 404

Since my 279b1e1fcb403131377a.worker.js is inside /dist its giving me 404 error. How can i make the request to go inside /dist .

There are plenty of examples given on the official Github page:

https://github.com/webpack-contrib/worker-loader

That should easily get you going.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM