linddss
linddss

Reputation: 83

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

Upvotes: 2

Views: 4324

Answers (3)

Nalbert Cerqueira
Nalbert Cerqueira

Reputation: 1

Try to do this:

//inside worker.js
self.addEventListener("message",(event)=>{
    importScripts("module.js")
    utils.print1()
    utils.print2()
})


//inside module.js
//setting a variable in global scope, allows worker.js to use it.
var utils = {
    print1(){
        console.log("This is a content from a module.")
    },
    print2(){
        console.log("This is a another content from a module.")
    }
}

Upvotes: 0

Alex Gusev
Alex Gusev

Reputation: 1854

Try this utils.js:

(function () {
    self.func1 = function (a, b) {
        return a + b
    }
}());

Upvotes: 1

Giulio Bambini
Giulio Bambini

Reputation: 4755

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.

Upvotes: 1

Related Questions