Web Workers - How To Import Modules

落爺英雄遲暮 提交于 2019-12-04 22:20:53

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 Expected to be shipped with version 80)
  • Webkit
  • Edge *(Edge changed to chromium)

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.

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!