如何将 Service Worker 从 JS 迁移到 TS

How to migrate service worker from JS to 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

如何在Typescript文件中定义self?

tsconfig.json文件中需要添加webworker

{
 ....
  "compilerOptions": {
  "lib": [
    ...
    "webworker"
  ],...
}

添加 webworker 库后,可以使用 typescript 声明 self ServiceWorkerGlobalScope

ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker.

declare const self: ServiceWorkerGlobalScope;

如果您在 tsconfig.json 中将 isolatedModules 标志设置为 true,那么您还需要向服务工作者文件添加一些导入或导出指令,因为:

Typescript treats files without import/exports as legacy script files. As such files are not modules and any definitions they have get merged in the global namespace. isolatedModules flag forbids such files.

如果您不需要任何导入或导出生成文件的简便方法,请添加模块 export { };

最后可以在 sw.ts 文件中使用完整的打字稿语法。