首页 > 解决方案 > 如何将 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

如何在打字稿文件中定义自我?

标签: typescripteslintservice-worker

解决方案


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文件中使用完整的打字稿语法。


推荐阅读