Web Workers - How To Import Modules

前端 未结 4 1936
后悔当初
后悔当初 2020-12-14 00:37

I am using ES2015 Import / Export modules.

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

worker.js

i         


        
相关标签:
4条回答
  • 2020-12-14 00:58

    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.

    0 讨论(0)
  • 2020-12-14 01:00

    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)

    0 讨论(0)
  • 2020-12-14 01:08

    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!):

    • Firefox: Priority: Not set
    • Chromium Browsers:
      Dedicated Workers: Available since version 80
      Shared Workers: Available since version 83
      Service Workers: prio 3
    • Webkit: Priority: P2 Normal
    0 讨论(0)
  • 2020-12-14 01:08

    2020:

    Chrome 80 has shipped module workers in February 2020 (and Chrome 82 will ship modules for shared workers). Firefox/Safari do not support those features for now: tests

    You may use want to use import-from-worker lib to do the heavy lifting for you (for now, you need to check the support for modules in workers and do the fallback yourself).

    0 讨论(0)
提交回复
热议问题