npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@anilanar/sw-precache-webpack-plugin

v0.9.1-patched.2

Published

Webpack plugin for using service workers

Downloads

7

Readme

SW Precache Webpack Plugin

NPM version NPM downloads Dependency Status CircleCI

SWPrecacheWebpackPlugin is a webpack plugin for using service workers to cache your external project dependencies. It will generate a service worker file using sw-precache and add it to your build directory.

Install

npm install --save-dev sw-precache-webpack-plugin

Basic Usage

var path = require('path');
var SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');


module.exports = {
  context: __dirname,

  entry: {
    main: path.resolve(__dirname, 'src/index'),
  },

  output: {
    path: path.resolve(__dirname, 'src/bundles/'),
    filename: '[name]-[hash].js',
  },

  plugins: [
    new SWPrecacheWebpackPlugin(
      {
        cacheId: 'my-project-name',
        filename: 'my-service-worker.js',
        maximumFileSizeToCacheInBytes: 4194304,
        minify: true,
        runtimeCaching: [{
          handler: 'cacheFirst',
          urlPattern: /[.]mp3$/,
        }],
      }
    ),
  ]
}

This will generate a new service worker at src/bundles/my-service-worker.js. Then you would just register it in your application:

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

Another example of registering a service worker is provided by GoogleChrome/sw-precache

Configuration

You can pass a hash of configuration options to SWPrecacheWebpackPlugin:

plugin options:

  • filename: [String] - Service worker filename, default is service-worker.js
  • filepath: [String] - Service worker path and name, default is to use webpack.output.path + options.filename. This will overried filename. Warning: Make the service worker available in the same directory it will be needed. This is because the scope of the service worker is defined by the directory the worker exists.
  • staticFileGlobsIgnorePatterns: [RegExp] - Define an optional array of regex patterns to filter out of staticFileGlobs (see below)
  • mergeStaticsConfig: [boolean] - Merge provided staticFileGlobs and stripPrefixMulti with webpack's config, rather than having those take precedence, default is false.
  • minify: [boolean] - Set to true to minify and uglify the generated service-worker, default is false.
  • forceDelete: [boolean] - Pass force option to del, default is false.

sw-precache options:

  • cacheId: [String] - Not required but you should include this, it will give your service worker cache a unique name
  • directoryIndex: [String]
  • dynamicUrlToDependencies: [Object<String,Array<String>]
  • handleFetch: [boolean]
  • ignoreUrlParametersMatching: [Array<Regex>]
  • importScripts: [Array<String>] - Add [hash] if you want to import a file generated with webpack [hash] ex. ['dist/some-[hash].js']
  • logger: [function]
  • maximumFileSizeToCacheInBytes: [Number]
  • navigateFallbackWhitelist: [Array<RegExp>]
  • replacePrefix: [String] - Should only be used in conjunction with stripPrefix
  • runtimeCaching: [Array<Object>]
  • staticFileGlobs: [Array<String>] - Omit this to allow the plugin to cache all your bundles' emitted assets. If mergeStaticsConfig=true: this value will be merged with your bundles' emitted assets, otherwise this value is just passed to sw-precache and emitted assets won't be included.
  • stripPrefix: [String] - Same as stripPrefixMulti[stripPrefix] = ''
  • stripPrefixMulti: [Object<String,String>] - Omit this to use your webpack config's output.path + '/': output.publicPath. If mergeStaticsConfig=true, this value will be merged with your webpack's output.path: publicPath for stripping prefixes. Otherwise this property will be passed directly to sw-precache and Webpack's output path won't be replaced.
  • templateFilePath: [String]
  • verbose: [boolean]

Note that all configuration options are optional. SWPrecacheWebpackPlugin will by default use all your assets emitted by webpack's compiler for the staticFileGlobs parameter and your webpack config's {[output.path + '/']: output.publicPath} as the stripPrefixMulti parameter. This behavior is probably what you want, all your webpack assets will be cached by your generated service worker. Just don't pass any arguments when you initialize this plugin, and let this plugin handle generating your sw-precache configuration.

Examples

See the examples documentation for more examples.

The simplest use case would be:

module.exports = {
  ...
  plugins: [
    new SWPrecacheWebpackPlugin(),
  ],
  ...
}

Here's an example using one option from sw-precache (cacheId) with one option from SWPrecacheWebpackPlugin (filename) in a configuration hash:

plugins: [
  new SWPrecacheWebpackPlugin(
    {
      cacheId: "my-project-name",
      filename: "my-project-service-worker.js",
    }
  ),
]

Here's a more elaborate example with mergeStaticsConfig: true and staticFileGlobsIgnorePatterns. mergeStaticsConfig: true allows you to add some additional static file globs to the emitted ServiceWorker file alongside Webpack's emitted assets. staticFileGlobsIgnorePatterns can be used to avoid including sourcemap file references in the generated ServiceWorker.

plugins: [
  new SWPrecacheWebpackPlugin(
    {
      cacheId: "my-project-name",
      filename: "my-project-service-worker.js",
      staticFileGlobs: [
        'src/static/img/**.*',
        'src/static/styles.css',
      ],
      stripPrefix: 'src/static/', // stripPrefixMulti is also supported
      mergeStaticsConfig: true, // if you don't set this to true, you won't see any webpack-emitted assets in your serviceworker config
      staticFileGlobsIgnorePatterns: [/\.map$/], // use this to ignore sourcemap files
    }
  ),
]

Webpack Dev Server Support

Currently SWPrecacheWebpackPlugin will not work with Webpack Dev Server. If you wish to test the service worker locally, you can use simple a node server see example project or python SimpleHTTPServer from your build directory. I would suggest pointing your node server to a different port than your usual local development port and keeping the precache service worker out of your local configuration (example).

Contributing

Install node dependencies:

  $ npm install

Add unit tests for your new feature in ./test/plugin.spec.js

Testing

Tests are located in ./test

Run tests:

  $ npm t