Search code examples
javascriptweb-worker

How to get js function into webWorker via importScripts


I have a worker.js file:

self.importScripts('/static/utils/utils.js')

onmessage = (e) => {
    let a = e.data[0]
    let b = e.data[1]
    let c = func1(a,b)
    postMessage(c)
}

The utils.js file looks something like this:

module.exports = {
func1: function(a,b){
    return a+b
}

I keep getting error:

Uncaught ReferenceError: module is not defined
    at utils.js:1

Obviously require, and import and any other server side imports aren't working but I'm not sure why it's having a problem with my importScripts - https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts


Solution

  • The correct solution is to pack your worker with webpack. If you don't want to do that, read below.

    I usually write myself a polyfill for node require:

    // This will not work in normal UI thread
    // None of this should make it into production
    function require(moduleName) {
        self.module = { exports: null };
        // Nasty sttuff right here, probably should throw error instead
        if (moduleName == "fs")
            return null;
        // This part is especially unprofessional
        if (!moduleName.endsWith(".js"))
            moduleName += ".js";
    
        importScripts(moduleName);
        return self.module.exports;
    }
    

    This makes use of the fact that importScripts is synchronous. Note that this will still cause errors if you try to load native node modules (eg. fs) or if other module properties are used.