如何在带有打字稿的 vue-cli 中使用自定义服务工作者事件

Cel*_*dus 6 typescript service-worker vue-cli

我有一个 Vue-cli 项目,并希望启用离线支持(pwa,渐进式 Web 应用程序功能)。因此我为 vue cli 安装了 PWA-Plugin。

在 vue.config.js 中,我配置了 Pwa 和工作箱,如下所示:

...
pwa: {
    name: 'projectname',
    // configure the workbox plugin
    // workboxPluginMode: 'GenerateSW',
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
      // swSrc is required in InjectManifest mode.
      swSrc: 'src/service-worker.js',
      }
}
...
Run Code Online (Sandbox Code Playgroud)

现在我想将我的以下附加事件注入服务工作者(来自 src/service-worker.js)

self.addEventListener('push', function (event) {
    console.log('[Service Worker] Push Received.');
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
});

self.addEventListener('fetch', function (event) {
    console.log(event.request.url);
    // event.respondWith(() => {
    //     fetch(event.request)
    // }
    // );
});
Run Code Online (Sandbox Code Playgroud)

在 registerServiceWorker.ts 中,我评论了环境检查,因此 service-worker 也在我的本地主机上提供服务。

/* eslint-disable no-console */
import { register } from 'register-service-worker'
// if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n'
      )
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
// }
Run Code Online (Sandbox Code Playgroud)

但是当我检查提供给浏览器的 service-worker.js 时,我只看到默认的 service-worker

/* eslint-disable no-console */
import { register } from 'register-service-worker'
// if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n'
      )
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
// }
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像:

/* eslint-disable-next-line no-redeclare */
/* global self */

// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.

// It is read and returned by a dev server middleware that is only loaded
// during development.

// In the production build, this file is replaced with an actual service worker
// file that will precache your site's local assets.

self.addEventListener('install', () => self.skipWaiting())

self.addEventListener('activate', () => {
  self.clients.matchAll({ type: 'window' }).then(windowClients => {
    for (const windowClient of windowClients) {
      // Force open pages to refresh, so that they have a chance to load the
      // fresh navigation response from the local dev server.
      windowClient.navigate(windowClient.url)
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

我尝试过的其他事情:

  • 使用 src/service-worker。ts而不是 js 文件没有帮助。
  • 使用“vue-cli-service serve --mode production”也会返回错误的服务工作者。
  • 当我将附加代码放在公共文件夹中并手动注册服务工作者时,我让“推送”测试正常工作,但离线缓存显然不起作用。

Cel*_*dus 2

我要做的第一件事是将“devserver”添加到vue.config.js

  devServer: {    
    https: true,
  },
  pwa: {
    // configure the workbox plugin
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
      swSrc: 'src/service-worker.js',
      swDest: 'service-worker.js',
    }
  }
...
Run Code Online (Sandbox Code Playgroud)

此外,我无法在没有证书错误的情况下运行 vue-cli 服务并为生产环境提供服务(即使我通过生产模式构建,并在 / dist文件夹中使用正确的服务工作人员)。

我当前的解决方法是使用 .NetCore 应用程序,将代码复制到wwwroot,然后使用 IISExpress 运行解决方案。我用npm run ship

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "copydist": "xcopy .\\dist ..\\wwwroot\\ /s /y",
    "ship": "npm run build && npm run copydist",
    "test": "set NODE_ENV=production && npm run build && serve -s dist"
  },
Run Code Online (Sandbox Code Playgroud)

我还没弄清楚的事情是:

  • 我如何为服务人员使用打字稿。
  • 如何使用有效的本地主机证书避免 .NetCore 解决方法。