typescript - 我如何在 Vue 3 中使用 vite-plugin-pwa 实现 typescript service worker

标签 typescript progressive-web-apps vuejs3 workbox vite

我想让一个单页应用程序可供离线使用。所以我想在我的 Vue webapp 中使用 PWA Service Worker,并为其使用 typescript 和 workbox。我遵循了 https://vite-plugin-pwa.netlify.app/guide/inject-manifest.html#typescript-support 中的示例.

在构建 typescript 时,我遇到了很多 TS2403 错误,例如:

node_modules/typescript/lib/lib.webworker.d.ts:5720:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onoffline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.
// ...
Found 21 errors in 2 files.

Errors  Files
     3  node_modules/typescript/lib/lib.dom.d.ts:25
    18  node_modules/typescript/lib/lib.webworker.d.ts:25
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! vite-project@0.0.0 build: `vue-tsc --noEmit && vite build`
npm ERR! Exit status 2

这是我执行的步骤。

我做的第一件事是安装 Vite 插件:

npm i vite-plugin-pwa -D

然后到 vite.config.ts 我添加了

import { VitePWA } from "vite-plugin-pwa";
//...
VitePWA({
    strategies: 'generateSW', // default
    includeAssets: [ "favicon.svg", /* ... */ ],
    manifest: {
      name: "Name of your app", 
      // ...
    },
}),
// ...

这里的第一个构建工作正常,但在接下来的步骤中我得到了错误。

现在在 vite.config.ts 中我添加了使用 typescript 的配置

VitePWA({
    srcDir: 'src',
    filename: 'sw.ts',
    workbox: { 
        swDest: "sw.js"
    },
    strategies: 'injectManifest', // changed
    // ...

然后更改 tsconfig.json(将 WebWorker 添加到 lib 并添加类型):

//"lib": ["esnext", "dom" ], // before
"lib": ["esnext", "dom", "WebWorker"],
"types": ["vite-plugin-pwa/client"]

最后在 src 文件夹中添加了 sw.ts:

/// <reference lib="WebWorker" />
import { skipWaiting, clientsClaim } from "workbox-core"
import { precacheAndRoute } from "workbox-precaching";

declare const self: ServiceWorkerGlobalScope

precacheAndRoute(self.__WB_MANIFEST);
skipWaiting();
clientsClaim();

最佳答案

我建议删除 "WebWorker"来自你的 tsconfig.jsonlib属性,只需使用 /// <reference lib="webworker" />三斜杠指令添加 lib sw.ts 顶部的引用文件。

您可以看到 example project with this setup如果有帮助。

关于typescript - 我如何在 Vue 3 中使用 vite-plugin-pwa 实现 typescript service worker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71517829/

相关文章:

c# - 未找到 PWA 的 list JSON 404?

angular - 定期检查 service worker 更新

typescript :如何正确键入由 n 个 N 元组和 m 个 M 元组组成的数组?

typescript - 形式为 `<T extends E>` 的通用约束,其中 `E` 是 `enum` ?

javascript - 确保桌面上有后退按钮(Windows 10)PWA

javascript - 为我的应用程序提供服务时出现空白页面(Vue Router 4 - Vue 3)

javascript - Vue 3 : Why dom ref value is undefined when ref in Vue 3 template

javascript - 在 Objection.js 中以多对多方式插入额外字段

javascript - 将插件注册到库

vuejs3 - .eslintrc 错误解析错误 : Maximum call stack size exceeded