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

时间:2018-02-09 19:47:22

标签: javascript web-worker

我有一个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

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

2 个答案:

答案 0 :(得分:1)

正确的解决方案是使用webpack打包您的工作人员。如果您不想这样做,请阅读以下内容。

我经常给自己写一个polyfill for node require:

export default {
    computed: {
        returnToken(){
            return this.$store.getters.returnToken; // was getters.idToken
                                    // ^^^^^^^^^^^ --- changed this part
        }
    }
}

这利用了export default { computed: { returnToken(){ return this.$store.state.idToken; // was getters.idToken // ^^^^^ ------------ changed this part } } } 同步的事实。请注意,如果您尝试加载本机节点模块(例如// 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属性,这仍会导致错误。

答案 1 :(得分:0)

尝试以下utils.js

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