iamnotpotter
iamnotpotter

Reputation: 61

Creating a service worker in vue.js using workbox's injectmanifest crashes

I am trying to use vue.js's progressive web app capabilities by creating a custom service worker through workbox. Everytime I attempt to build the app I get the following error: 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);
  }
});

I have tried changing the formatting on swSrc to lead with ./ or just / and even removing src/ but none of these have done anything. I have also tried coping code generated by workbox, then pasting it into service-worker.js, but it still does not recognize it. How do I get InjectManifest to recognize my my service worker file?

Upvotes: 2

Views: 4142

Answers (1)

iamnotpotter
iamnotpotter

Reputation: 61

I answered my own question. I needed to change project/vue.config.js to

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

Upvotes: 4

Related Questions