Web Workers - How To Import Modules

Kayote picture Kayote · May 22, 2017 · Viewed 20.9k times · Source

I am using ES2015 Import / Export modules.

In my worker file, when I try to import functions like I normally do:

worker.js

import { a, b, c } from "./abc.js";

I get the error: SyntaxError: import declarations may only appear at top level of a module

As I am exporting functions in my module 'abc.js', I am not sure how to use them using the old (& apparently on its way out) syntax:

self.importScripts( "/app/abc.js" );

So, my question is, how do we use the new import module syntax with workers?

Second question is, what does importScripts import into when it imports from a module in where is there is no global object parent being exported?

Answer

Tobias Buschor picture Tobias Buschor · Aug 9, 2017

ES2015 modules in Workers are currently implemented in chromium only.
For other browsers you have to use importScripts().

You create a worker like this:

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

See: https://html.spec.whatwg.org/#module-worker-example

These are the bug-reports for each browser (please vote!):