sw-precache-webpack-plugin icon indicating copy to clipboard operation
sw-precache-webpack-plugin copied to clipboard

Provide option to auto generate register bundle script

Open goldhand opened this issue 8 years ago • 1 comments

When a user opts in, emit a bundle with a registration script.

API:

  ...
  output: {
    path: path.resolve(__dirname, 'dist/'),
    filename: '[name]-[hash].js',
    publicPath: 'http://localhost:3000/',
  },
  plugins: [
    new SWPrecacheWebpackPlugin(
      {
        cacheId: 'my-project-name',
        filename: 'my-service-worker.js'
        register: true,
      }
    ),
  ],
  ...

emits: dist/register-sw-[hash].js

(function() {
  if('serviceWorker' in navigator) {
    navigator.serviceWorker.register('http://localhost:3000/my-service-worker.js');
  }
})();

This has the added benefit of being picked up by webpack template plugins that inject all bundles into an html template (html-webpack-plugin #62)

goldhand avatar Apr 09 '17 19:04 goldhand

apply(compiler) {
    const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin');
    compiler.plugin("entry-option", (context, entry) => {
      compiler.apply(new SingleEntryPlugin('./', 'register-service-worker', 'register-service-worker'));
    });
}

goldhand avatar Sep 10 '17 22:09 goldhand