[英]Use ESM in a service worker file (import/export)
I am trying to use a service worker file which is also an ESM module.我正在尝试使用一个服务工作者文件,它也是一个 ESM 模块。
The register
method has an extra argument accepting an options
object which has a type
field whose valid values seem to be classic
and module
, but when I use: register
方法有一个额外的参数,它接受一个options
对象,该对象具有一个type
字段,其有效值似乎是classic
和module
,但是当我使用时:
navigator.serviceWorker.register('worker.js', { type: 'module' });
// `worker.mjs` doesn't work either
// The file exists in both cases!
I get an unspecified DOMException
with no message in Chrome.我在 Chrome 中收到一个未指定的
DOMException
且没有消息。
I figured what the valid values for type
were by reading the spec, specifically this:我想出什么有效的值
type
是通过读取规格,具体如下:
https://html.spec.whatwg.org/multipage/workers.html#workertype https://html.spec.whatwg.org/multipage/workers.html#workertype
It seems to me like my code is valid.在我看来,我的代码是有效的。
As a sanity check, I also tried to explicity set type
to classic
and the service worker registration then goes through fine.作为完整性检查,我还尝试将
type
显式设置为classic
,然后服务人员注册就可以正常进行了。 If I set it to an invalid value, I get a TypeError
telling me so, so it's not like the browser is not yet aware of type: module
.如果我将它设置为无效值,我会收到一个
TypeError
告诉我,所以浏览器并不知道type: module
。 It is treated as a special case, it just throws a DOMException
with no message.它被视为一种特殊情况,它只是抛出一个没有消息的
DOMException
。
Am I using the type
field correctly?我是否正确使用了
type
字段? Is it still too early and it is not supported in browsers?现在还为时过早,浏览器不支持吗?
This is dumb!这是愚蠢的! Chrome will print just
DOMException
into the console (not even expansible) when logging the error object and Object.keys
on that object instance returns []
, but when I specifically print e.message
the culprit is revealed:当记录错误对象和对象实例上的
Object.keys
返回[]
,Chrome 将仅将DOMException
打印到控制台(甚至不可扩展),但是当我专门打印e.message
,罪魁祸首就暴露了:
type 'module' in RegistrationOptions is not implemented yet.See https://crbug.com/824647 for details.
尚未实现 RegistrationOptions 中的类型“模块”。有关详细信息,请参阅https://crbug.com/824647 。
Not amused by Chrome.没有被 Chrome 逗乐。
On browsers, bare names can't be used to identify modules unless you also have a module map (aka import map , this link has much more info) that maps the bare name to a module.在浏览器上,裸名称不能用于标识模块,除非您还有将裸名称映射到模块的模块映射(又名import map ,此链接有更多信息)。
If worker.js
is in the same location as the page loading it, then:如果
worker.js
与加载它的页面位于同一位置,则:
navigator.serviceWorker.register('./worker.js', { type: 'module' });
// -------------------------------^^
Or of course, add a module map.或者当然,添加一个模块映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.