如何在 Vue 3 中使用 vite-plugin-pwa 实现 TypeScript Service Worker

Cel*_*dus 9 typescript progressive-web-apps workbox vuejs3 vite

我想制作一个可离线使用的单页应用程序。所以我想在我的 Vue web 应用程序中使用 PWA Service Worker 并使用 typescript 和 workbox。我按照https://vite-plugin-pwa.netlify.app/guide/inject-manifest.html#typescript-support中的示例进行操作。

在构建打字稿时,我遇到很多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
Run Code Online (Sandbox Code Playgroud)

这是我所做的步骤。

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

npm i vite-plugin-pwa -D
Run Code Online (Sandbox Code Playgroud)

然后vite.config.ts我添加了

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
Run Code Online (Sandbox Code Playgroud)

此处的第一次构建工作正常,但在接下来的步骤中我收到错误。

现在,vite.config.ts我添加了使用打字稿的配置

npm i vite-plugin-pwa -D
Run Code Online (Sandbox Code Playgroud)

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

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

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

VitePWA({
    srcDir: 'src',
    filename: 'sw.ts',
    workbox: { 
        swDest: "sw.js"
    },
    strategies: 'injectManifest', // changed
    // ...
Run Code Online (Sandbox Code Playgroud)

Jef*_*ick 2

我建议"WebWorker"从您的tsconfig.json属性中删除lib,然后使用三斜杠指令在文件顶部/// <reference lib="webworker" />添加引用。libsw.ts

如果有帮助,您可以查看使用此设置的示例项目。

  • 感谢您提供示例项目的提示。从库中删除“WebWorker”就完成了一半。为了解决这个问题,我必须在 `tsconfig.json` 中添加 `"exclude": ["src/sw.ts"],`。排除该文件不是不好的做法吗?然后我就可以编写类型不安全的代码。 (2认同)