我想让一个单页应用程序可供离线使用。所以我想在我的 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.json
的 lib
属性,只需使用 /// <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/