如何通过 importScripts 将 js 函数导入 webWorker

How to get js function into webWorker via importScripts

我有一个 worker.js 文件:

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)
}

utils.js 文件看起来像这样:

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

我不断收到错误消息:

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

显然 require、import 和任何其他服务器端导入都不起作用,但我不确定为什么我的 importScripts 有问题 - https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts

正确的解决方案是用 webpack 打包你的 worker。如果您不想这样做,请阅读下文。

我通常会为自己编写一个 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;
}

这利用了 importScripts 是同步的事实。请注意,如果您尝试加载本机节点模块(例如 fs)或使用其他 module 属性,这仍然会导致错误。

试试这个 utils.js:

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