5

I've got a WebWorker in which I want to use functions from another existing JavaScript file. I've tried different methods to import the JS file but so far none have worked. The file in question is in another directory, with relate path '../pkg/benchmark.js'.

Is there anyone who knows how to do this?

I've tried the following methods:

Method 1:

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

which gives the errors:

Uncaught SyntaxError: Unexpected token *

Method 2:

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

gives the error:

Uncaught SyntaxError: Unexpected token {

Method 3: Using importScripts()

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

gives the error:

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

Method 4: Using dynamic imports:

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

gives the error:

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

Since I'm using npm, it should be mentioned that in package.json I've defined the dependency

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

so I normally don't have to specify the relative path, and instead just import 'benchmark' directly. This doesn't work either.

Method 5: Finally, I've tried enabling the chrome flag

--enable-experimental-web-platform-features

and declare my worker as

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

which doesn't give any errors in the developer console but also doesn't run the imported functions.

ryougi1
  • 89
  • 7

0 Answers0