3

The pattern for a script used by a webworker https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers is:

  • webworker.js

    importScripts('./parent.js') 
  • parent.js

    import { PerfManager} from "./child.js"; 

The child.js import results in:

Uncaught SyntaxError: Cannot use import statement outside a module

Is there any way to implement an import within the parent.js when used by webworker.js ?

1
  • if you want to use import instead of importScripts you need to use babel to compile parent.js and then use importScript('./compile.parent.js') Commented Sep 25, 2020 at 20:17

1 Answer 1

4

You can start a module Worker (currently only available in Blink based browsers).

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

Then instead of importScripts you will directly import parent.js from this worker script, which will in turn be able to import whatever dependency.

Since StackSnippets are in null-origined iframes, I have to outsource the demo to this plnkr.


Note that in these browsers you could even use the dynamic import() statement from parent.js even in a non module Worker: plnkr, but this still wouldn't work in browsers that don't support module Workers.
For these you need to use only non module scripts and to use importScripts and its globals all along the chain: plnkr.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm on chrome: it does support module workers and in fact we are using them now. But the transient dependencies are not being accepted - at least not in Intellij. Is that then IJ being too picky?
Might be indeed, I really don't know this IDE, but it should work as demonstrated in the plunkers;.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.