Blue_Dragon360 Blue_Dragon360 - 20 days ago 11
Node.js Question

How do I require() web workers in npm?

I've got a npm/webpack setup, and part of my application requires Web Workers. Normally, web workers are created with this syntax:

var worker = new Worker('path/to/external/js/file.js');


In npm, this doesn't work, because the development environment I'm using doesn't accept paths like this. Files must be included using
require()
.

I can't just link to the file absolutely, since that violates the cross-origin rule thing.

Is there a strategy for including these worker files?

Answer

The worker-loader loader provided by Webpack seems to provide a solution to your problem. This module can be installed with npm install --save-dev worker-loader.

Take a look at how to use loaders, then require your web worker files like so:

const Foo = require("worker!./path/to/external/js/file.js");
const fooWorker = new Foo();

Note the worker! prepended before the path, which tells Webpack to use the worker loader specifically.

You should be able to require modules normally in the worker file itself also, provided your setup is correct.

Comments