john doe
john doe

Reputation: 557

Can I use modules in a web worker?

For the first time, I developed a project using the "new" native import and export features and all my modules are written that way.

Well now I want to add a feature to run some of those modules via a web worker. Is it doable without duplicating the modules and altering them (creating a maintenance nightmare)?

For example, I know about the importScripts functionality in web workers, but the documentation doesn't say anything about it playing nice with module exports.

So if I have a file like this:

import // ... resources ...

function doStuff() {
    // do stuff that a web worker can handle, no DOM manip, etc
}

export default doStuff;

Can it be seamlessly utilized inside a web worker, assuming none of its components do things that a web worker can't?

If not, could I use something like webpack to bundle the module together into a single web worker file? Is there some common way of doing this?

Upvotes: 4

Views: 3353

Answers (1)

john doe
john doe

Reputation: 557

Didn't plan on self answering this but I did some testing on that webpack idea and yes, even if you don't want to use webpack for your whole project, which I don't, you can use it with the web worker being your entry point, pull all the needed modules into one file with webpack, and use the output file as a web worker.

I wasn't sure webpack was going to output a web-worker-friendly file, but it does and so you can use something like this and it'll work perfectly if you webpack it:

import testFunc from './test.js';

onmessage = function(e) {
    testFunc();
    console.log('Message received from main script:', e.data);
    var workerResult = 'hello world';
    console.log('Posting message back to main script');
    postMessage(workerResult);
}

I tested this and it absolutely works when ran as a web worker in web packed form.

Upvotes: 4

Related Questions