Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - Web Workers - How To Import Modules

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ES2015 modules in Workers are available in Desktop Safari and in Chromium browsers.

If other browsers / versions are your target, you still need to use importScripts().

When available, you create a module-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:

  • Firefox: In development ?? please vote!
  • Chromium Browsers:
    Dedicated Workers: Available since version 80 ??
    Shared Workers: Available since version 83 ??
    Service Workers: Available since version 91 ??
  • Webkit:
    Safari Desktop: Available since Safari 14.1 ??
    Safari Mobile (iOS): Available since Safari 15 ??

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...