Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack Worker Loader: How to make it work as a dependency?

I have my index.html importing a dependency.

<script src="node_modules/myModule/app.js"></script> 

myModule/app.js

var WebWorker = require('worker-loader!./worker');
window.WebWorker = new WebWorker();

The worker exists in node_modules/myModule/worker.js

When I run 'webpack' it works, as they are on the same folder. If I change anything in the path, webpack wouldn't pick up the webworker code as needed.

Problems comes when using this modules as a dependency, because I need to place worker.js in the same route as the index.html.

The alternative is using a Blob and insert the worker as an Inline dependency, but they are not supported on IE11.

Thus, I don't know if there's a good option to make it work.

like image 961
Chexpir Avatar asked Feb 13 '17 12:02

Chexpir


People also ask

How do you use webpack loaders?

They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs.

How many web workers can run concurrently?

How many web workers can run concurrently JavaScript? A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.

What is raw loader?

The RAW Loader is the easiest yet most effective way to scoop up loose material from your tray and load it into your cone or paper. The simplicity of the Raw Loader is what makes it such a Rawesome tool that is a must for all RYO enthusiasts. Included with the RAW Loader is a non-stick scraper and a long bamboo poker.


1 Answers

you should choose a naming pattern for your workers, let's say:

myWorkerModule.worker.js

And then configure the webpack worker loader to handle all the file with that pattern. Here is the relevant part of the webpack.config:

module: {
    rules: [
        {
            test: /\.worker\.js$/,
            use: { loader: 'worker-loader' }
        }
    ]
}

Now when you need that worker module as a dependency, simply put

var myWorkerModule = require('./myWorkerModule.worker')

or

import myWorkerModule from './myWorkerModule.worker'

Hope it helps.

like image 193
Ed_le_fou Avatar answered Sep 17 '22 11:09

Ed_le_fou