khalyomede / gridsome-plugin-service-worker

Registers a service worker and apply your file strategies to let you build a PWA.
https://npmjs.com/package/gridsome-plugin-service-worker
MIT License
8 stars 2 forks source link
gridsome-plugin network-strategy pwa service-worker

gridsome-plugin-service-worker

Registers a service worker and apply your file strategies to let you build a PWA.

npm npm peer dependency version NPM Build Status codecov Snyk Vulnerabilities for npm package Libraries.io dependency status for latest release Maintainability

Summary

About

I created this plugin because I needed a flexible way to add a service worker into my web app, and without having all the unpleasing setup (importing the library, registering my service worker, adding the files to the head, ...).

I wanted to have a drop-in way to tell which routes to capture and for each, to decide which specific network strategy.

Features

Requirements

Installation

With NPM

npm install --save-dev gridsome-plugin-service-worker

With Yarn

yarn add --dev gridsome-plugin-service-worker

Usage

This section assumes you already installed Gridsome.

Add the plugin to the list of your plugins in the file gridsome.config.js

module.exports = {
  siteName: "Gridsome",
  plugins: [
    {
      use: "gridsome-plugin-service-worker",
    },
  ],
};

Add a first network strategy, which will serve as an example that you will be able to tweak later.

module.exports = {
  siteName: "Gridsome",
  plugins: [
    {
      use: "gridsome-plugin-service-worker",
      options: {
        networkFirst: {
          routes: ["/", "/about"],
          fileTypes: ["document", "script", "style", "image"],
        },
      },
    },
  ],
};

Run this command to build your project.

With NPM

npm run build

With Yarn

yarn build

Serve the files locally, and navigate to the home page. Simulate a connection shutdown by going in the Chrome DevTools panel, in the "Network" tab, then choose "Offline" in the dropdown.

Reload your page: you should still see your home page, which means the service worker successfully fetched your resources from the cache as a fallback.

Whenever you use your CacheFirst (for example), but you still need your files to be fetched again because you made a change on these files, you should change the name of the cache (using the cacheName option in gridsome.config.js) in order for the service worker to "update" the cache.

Lastly (optional), configure your server (if your server architecture allow you to do so) to prevent the files /service-worker.js and /assets/js/service-worker.js to be cached by your server. Here is an example using Apache:

<Files /service-worker.js>
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</Files>

<Files /assets/js/service-worker.js>
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</Files>

The browsers now are configured to check every 24h at most for service worker changes, but this operations make sure the browser will not try to cache these files anyway.

Examples

1. Use a Network-First strategy

// gridsome.config.js
module.exports = {
  plugins: [
    {
      use: "gridsome-plugin-service-worker",
      options: {
        networkFirst: {
          cacheName: "nf-v1",
          routes: ["/", /\.(js|css|png)/],
        },
      },
    },
  ],
};

2. Cache resources ahead of time for offline browsing

// gridsome.config.js
module.exports = {
  plugins: [
    {
      use: "gridsome-plugin-service-worker",
      options: {
        precachedRoutes: ["/"],
        cacheOnly: {
          cacheName: "co-v1",
          routes: ["/"],
        },
      },
    },
  ],
};

3. Caching file types instead of routes

// gridsome.config.js
module.exports = {
  plugins: [
    {
      use: "gridsome-plugin-service-worker",
      options: {
        networkFirst: {
          cacheName: "nf-v1",
          fileTypes: [
            "document", // includes HTML files
            "image",
            "script",
            "style",
          ],
        },
      },
    },
  ],
};

You can mix file types and routes if you need.

For a list of available fileTypes, check the Mozilla Developer Network documentation on Service worker request destinations.

API

You will find the prototype of the Strategy type below.

interface Strategy {
  cacheName: string;
  routes: Array<String | RegExp>;
  fileTypes: Array<RequestDestination>;
}
type RequestDestination =
  | ""
  | "audio"
  | "audioworklet"
  | "document"
  | "embed"
  | "font"
  | "image"
  | "manifest"
  | "object"
  | "paintworklet"
  | "report"
  | "script"
  | "serviceworker"
  | "sharedworker"
  | "style"
  | "track"
  | "video"
  | "worker"
  | "xslt";

Run the tests

  1. Clone the project: git clone https://github.com/khalyomede/gridsome-plugin-service-worker.git

  2. Install the dependencies

    • With NPM: npm install
    • With Yarn: yarn install
  3. Run the tests

    • With NPM: npm run test
    • With Yarn: yarn test