使用工作箱的注入清单崩溃在vue.js中创建服务工作人员

我正在尝试使用vue.js的渐进式Web应用程序功能,通过Workbox创建自定义服务工作者。每次我尝试构建应用程序时,都会收到以下错误: AssertionError [ERR_ASSERTION]: swSrc must be set to the path to an existing service worker file.

project/vue.config.js:

module.exports = {
  runtimeCompiler: true,
  pwa: {
    workboxPluginMode: "InjectManifest",
    plugins: [
      new InjectManifest({
        swSrc: "src/service-worker.js"
      })
    ]
  }
};

project/src/service-worker.js:

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

//Web Push Notifications//
let click_open_url;
self.addEventListener("push", function(event) {
  let push_message = event.data.json();
  // push notification can send event.data.json() as well
  click_open_url = push_message.notification.data.url;
  const options = {
    body: push_message.notification.body,
    icon: push_message.notification.icon,
    image: push_message.notification.image,
    tag: "alert"
  };
  event.waitUntil(
    self.registration.showNotification(push_message.notification.title, options)
  );
});

self.addEventListener("notificationclick", function(event) {
  const clickedNotification = event.notification;
  clickedNotification.close();
  if (click_open_url) {
    const promiseChain = clients.openWindow(click_open_url);
    event.waitUntil(promiseChain);
  }
});

我尝试将swSrc上的格式更改为以./开头或仅以/开头,甚至删除了src/,但这些都没有效果。我还尝试了复制Workbox生成的代码,然后将其粘贴到service-worker.js中,但它仍然无法识别它。如何让InjectManifest识别我的服务工作者文件?


解决方案

我回答了自己的问题。我需要将project/vue.config.js更改为

module.exports = {
  runtimeCompiler: true,
  pwa: {
    workboxPluginMode: "InjectManifest",
    workboxOptions:{
      swSrc: "src/service-worker.js"
  }
};

相关文章