Home

Awesome

serviceworker-webpack-plugin

Simplifies creation of a service worker to serve your webpack bundles.

npm version npm downloads Build Status

Dependencies DevDependencies

Installation

npm install serviceworker-webpack-plugin

The problem solved

When building a service worker, you probably want to cache all your assets during the install phase. But in order to do so, you need their names. That's not simple when you are using Webpack:

Setup

1. Add the plugin to your webpack config

import ServiceWorkerWebpackPlugin from 'serviceworker-webpack-plugin';

...

  plugins: [
    new ServiceWorkerWebpackPlugin({
      entry: path.join(__dirname, 'src/sw.js'),
    }),
  ],

2. Register the service worker in your main JS thread

import runtime from 'serviceworker-webpack-plugin/lib/runtime';

if ('serviceWorker' in navigator) {
  const registration = runtime.register();
}

3. Write your own sw.js

You can now use the global serviceWorkerOption variable in your sw.js. E.g. In our example this object looks like:

{
  assets: [
    './main.256334452761ef349e91.js',
  ],
}

Simple example

You can have a look at the /docs folder if you need a full working example.

API

ServiceWorkerWebpackPlugin(options)

runtime(options)

Credit

Why simply not use the offline-plugin?

I wouldn't have been able to write this plugin without the offline-plugin project. Thanks @NekR for sharing it!

Still, soon after using it, I realized that it wasn't what I was looking for.

Hence, I decided to change the approach and created this thin layer on top of Webpack to solve the assets name issue. Nothing more.

If you don't care about my two issues with offline-plugin then you don't need to use this package, offline-plugin is great.

The specs

License

MIT