webpackservice-workermanifestworkboxworkbox-webpack-plugin

What is sw.js for workbox-webpack-plugin.InjectManifest supposed to include?


I'm trying to use workbox-webpack-plugin.InjectManifest and all the examples I find look something like the code below, but I can't find an example of what src/sw.js is supposed to look like. I tried searching for example's of service worker files and feel like I might be starting a goose chase learning way more about service workers that I need to without actually getting an example. All I'm trying to do is include my manifest settings with my service worker. I thought I would be able to do this, considering the name of the function is called InjectManifest

// Inside of webpack.config.js:
const {InjectManifest} = require('workbox-webpack-plugin');

module.exports = {
  // Other webpack config...
  plugins: [
    // Other plugins...
    new InjectManifest({
      swSrc: './src/sw.js',
    })
  ]
};

Manifest.js (Extra, if it's useful)

const Icon192 = require("../images/icon-192x192.png");
const Icon512 = require("../images/icon-512x512.png")

const manifest = {
  icons: [
    {
      src: Icon192,
      sizes: "192x192",
      type: "image/png",
    },
    {
      src: Icon512,
      sizes: "512x512",
      type: "image/png",
    },
  ],
  name: "My_App",
  short_name: "My_App",
  orientation: "portrait",
  display: "standalone",
  start_url: "/",
  theme_color: "    #228B22",
  background_color: "#ffffff",
  description: "Any Maskable",
  start_url: "https://example.com",
  display: "browser",
  prefer_related_applications: false
};

module.exports = JSON.stringify(manifest, null, 2);


Solution

  • It very much depends on the functionality you'd like in your service worker. This section of the Workbox getting started guide walks through a few use cases, including precaching and runtime caching, and the accompanying code is what would appear in your sw.js file.

    At its most basic, if all you're interested in is precaching all of the assets in your webpack build, the following could be used as your sw.js:

    import { precacheAndRoute } from 'workbox-precaching';
    
    precacheAndRoute(self.__WB_MANIFEST);