Web Workers - How To Import Modules

2019-06-14 23:22发布

问题:

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?

回答1:

ES2015 modules in workers are not yet supported in any browser (not even ones that support modules otherwise). Once they do, you have to create a worker like this:

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

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

For now you have to use importScripts().

These are the bug-reports for each browser:

  • Firefox
  • Chromium (it's currently behind a flag: --enable-experimental-web-platform-features)
  • Webkit
  • Edge (also this uservoice page)


回答2:

ES Modules in workers are already available in Chrome, enabling Experimental Web Platform Features, using the proper flag when launching chrome:

chrome.exe --enable-experimental-web-platform-features

This is the syntax you need to use to load the worker script as a module :

new Worker( 'my-worker.js', { type : 'module' } );

This feature has been in development for almost ayear, and should be available soon, without the need of special flags, however, there is no official release date yet.



回答3:

for me assigning to self. worked well. I've put import to another js file: abcImported.js

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

export {  a, b, c };

and in the service worker:

self.a = require('abcImported.js').a;
self.b = require('abcImported.js').b;

in this way, it is accessible inside the worker. (tested in chrome)