如何在Web Worker中导入另一个JS文件?

时间:2019-07-03 15:01:45

标签: javascript web-worker javascript-import

我有一个WebWorker,我想在其中使用另一个现有JavaScript文件中的函数。我尝试了不同的方法来导入JS文件,但到目前为止没有一种方法有效。有问题的文件在另一个目录中,且具有相关路径“ ../pkg/benchmark.js”。

有谁知道该怎么做?

我尝试了以下方法:

方法1:

import * as myFile from '../pkg/benchmark.js';

出现错误:

Uncaught SyntaxError: Unexpected token *

方法2:

import { myFunc1, myFunc2 } from '../pkg/benchmark.js';

给出错误:

Uncaught SyntaxError: Unexpected token {

方法3: 使用importScripts()

importScripts('../pkg/benchmark.js');

给出错误:

worker_wasm.js:6 Uncaught DOMException: Failed to execute importScripts' on 'WorkerGlobalScope': The script at http://localhost:8080/pkg/benchmark.js' failed to load. 

方法4: 使用动态导入:

import('../pkg/benchmark.js')
    .catch(e => console.error(e));

给出错误:

TypeError: Failed to fetch dynamically imported module: http://localhost:8080/pkg/benchmark.js

因为我使用的是npm,所以应该提到在package.json中我已经定义了依赖项

"dependencies": {
    "benchmark": "file:../pkg"
  }

所以我通常不必指定相对路径,而是直接导入“基准”。这也不起作用。

方法5: 最后,我尝试启用chrome标志

--enable-experimental-web-platform-features

并将我的工作人员声明为

new Worker("worker.js", { type: "module" });

在开发者控制台中不会出现任何错误,但也不会运行导入的功能。

0 个答案:

没有答案