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

Javascript 如何在Web Worker中导入另一个JS文件?,javascript,web-worker,javascript-import,Javascript,Web Worker,Javascript Import,我有一个WebWorker,我想在其中使用另一个现有JavaScript文件中的函数。我尝试了不同的方法来导入JS文件,但到目前为止都没有成功。该文件位于另一个目录中,路径为“../pkg/benchmark.js” 有人知道怎么做吗 我尝试了以下方法: 方法1: import * as myFile from '../pkg/benchmark.js'; import { myFunc1, myFunc2 } from '../pkg/benchmark.js'; 其中给出了错误: Unc

我有一个WebWorker,我想在其中使用另一个现有JavaScript文件中的函数。我尝试了不同的方法来导入JS文件,但到目前为止都没有成功。该文件位于另一个目录中,路径为“../pkg/benchmark.js”

有人知道怎么做吗

我尝试了以下方法:

方法1:

import * as myFile from '../pkg/benchmark.js';
import { myFunc1, myFunc2 } from '../pkg/benchmark.js';
其中给出了错误:

Uncaught SyntaxError: Unexpected token *
方法2:

import * as myFile from '../pkg/benchmark.js';
import { myFunc1, myFunc2 } from '../pkg/benchmark.js';
给出了错误:

Uncaught SyntaxError: Unexpected token {
worker_wasm.js:6 Uncaught DOMException: Failed to execute importScripts' on 'WorkerGlobalScope': The script at http://localhost:8080/pkg/benchmark.js' failed to load. 
TypeError: Failed to fetch dynamically imported module: http://localhost:8080/pkg/benchmark.js
方法3: 使用importScripts()

给出了错误:

Uncaught SyntaxError: Unexpected token {
worker_wasm.js:6 Uncaught DOMException: Failed to execute importScripts' on 'WorkerGlobalScope': The script at http://localhost:8080/pkg/benchmark.js' failed to load. 
TypeError: Failed to fetch dynamically imported module: http://localhost:8080/pkg/benchmark.js
方法4: 使用动态导入:

import('../pkg/benchmark.js')
    .catch(e => console.error(e));
给出了错误:

Uncaught SyntaxError: Unexpected token {
worker_wasm.js:6 Uncaught DOMException: Failed to execute importScripts' on 'WorkerGlobalScope': The script at http://localhost:8080/pkg/benchmark.js' failed to load. 
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" });
这不会在开发人员控制台中给出任何错误,但也不会运行导入的函数