typescript - 如何将 service worker 从 JS 迁移到 TS
问题描述
设想
我想将我的 service-worker 文件从 javascript 更改为 typescript 以便更好地维护。这是我的 sw.js 文件:
/* eslint-disable no-console */
self.addEventListener("push", (event) => {
...
});
...more handlers
问题
我已经更改了很多行以使我的代码适应 TS 和 ESlint 要求,但是我遇到了self
来自 ESlint 的 2 个错误的问题:
unexpected use of 'self'
self is not defined
如何在打字稿文件中定义自我?
解决方案
在tsconfig.json
文件中需要添加webworker
库
{
....
"compilerOptions": {
"lib": [
...
"webworker"
],...
}
添加 webworker 库后,可以使用 typescript 声明 self ServiceWorkerGlobalScope
。
ServiceWorker API 的 ServiceWorkerGlobalScope 接口代表了一个服务工作者的全局执行上下文。
declare const self: ServiceWorkerGlobalScope;
如果您isolatedModules
在 tsconfig.json 中将 flag 设置为 true,那么您还需要在 service worker 文件中添加一些导入或导出指令,因为:
Typescript 将没有导入/导出的文件视为遗留脚本文件。由于此类文件不是模块,因此它们已合并到全局命名空间中的任何定义。isolatedModules 标志禁止此类文件。
如果您不需要任何导入或导出使文件成为模块的便捷方式,请添加export { };
描述此问题的堆栈问题
最后,可以在sw.ts
文件中使用完整的打字稿语法。
推荐阅读
- html - 为什么我的 SVG 图标在使用规则“vertical-align:middle”后没有垂直居中显示?
- erlang - 如何在 Erlang 中找到 utf8 编码二进制文件的字符长度?
- json - 我一直在尝试将 API 用于我一直在制作的股票网站,我的 api 有多个单词,它们之间有空格
- python - 给时间按下电报机器人中的 InlineKeyboardButton 按钮
- typescript - 如何在新标签中打开并使用 Cypres 切换到该标签?
- python - 在数据文件中的特定列上使用熊猫“.value_counts”
- python - 如何通过具有浮点值的“1”矩阵将其转换为“20000”?
- jinja2 - 如何将选择字段中的 form.data 作为烧瓶中的参数
- python - Python 错误:aiogram.dispatcher.dispatcher:获取更新时导致异常
- javascript - 如何禁用 div 内特定元素的悬停效果?