A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.npmjs.com/package/sw-precache-webpack-plugin below:

sw-precache-webpack-plugin - npm

SW Precache Webpack Plugin

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.

🚨 No longer being updated

I will try to keep this up-to-date with new webpack releases so feel free to keep using this if you like but I will not be adding any new features. I would recommend using workbox-webpack-plugins#GenerateSW which is actively being supported.

Install

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

Basic Usage

A simple configuration example that will work well in most production environments. Based on the configuration used in create-react-app.

var path = require('path');

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

 

const PUBLIC_PATH = 'https://www.my-project-name.com/';  

 

module.exports = {

 

  entry: {

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

  },

 

  output: {

    path: path.resolve(__dirname, 'src/bundles/'),

    filename: '[name]-[hash].js',

    publicPath: PUBLIC_PATH,

  },

 

  plugins: [

    new SWPrecacheWebpackPlugin(

      {

        cacheId: 'my-project-name',

        dontCacheBustUrlsMatching: /\.\w{8}\./,

        filename: 'service-worker.js',

        minify: true,

        navigateFallback: PUBLIC_PATH + 'index.html',

        staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],

      }

    ),

  ],

}

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

(function() {

  if('serviceWorker' in navigator) {

    navigator.serviceWorker.register('/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:

sw-precache options: Pass any option from sw-precache into your configuration. Some of these will be automatically be populated if you do not specify the value and a couple others will be modified to be more compatible with webpack. Options that are populated / modified:

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 or the implementation in create-react-app.

Simplest Example

No arguments are required by default, SWPrecacheWebpackPlugin will use information provided by webpack to generate a service worker into your build directory that caches all your webpack assets.

module.exports = {

  ...

  plugins: [

    new SWPrecacheWebpackPlugin(),

  ],

  ...

}

Advanced Example

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/', 

    mergeStaticsConfig: true, 

    staticFileGlobsIgnorePatterns: [/\.map$/], 

  }),

]

Generating Multiple Service Workers

If you have multiple bundles outputted by webpack, you can create a service worker for each. This can be useful if you have a multi-page application with bundles specific to each page and you don't need to download every bundle (among other reasons).

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

 

const APPS = {

  home: path.resolve(__dirname, 'src/home'),

  posts: path.resolve(__dirname, 'src/posts'),

  users: path.resolve(__dirname, 'src/users'),

}

 

const OUTPUT_DIR = 'dist';

 

module.exports = {

 

  entry: APPS,

 

  output: {

    path: path.resolve(__dirname, OUTPUT_DIR),

    filename: '[name].[hash].js',

  },

 

  plugins: [

    

    ...Object.keys(APPS)

      .map(app => new SWPrecacheWebpackPlugin({

        cacheId: `${app}`,

        filename: `${app}-service-worker.js`,

        stripPrefix: OUTPUT_DIR,

        

        

        

        staticFileGlobs: [

          `${OUTPUT_DIR}/js/manifest.*.js`,

          `${OUTPUT_DIR}/js/${app}.*.js`,

          `${OUTPUT_DIR}/css/${app}.*.css`,

          `${OUTPUT_DIR}/${app}.html`,

        ],

      })),

  ],

}

importScripts usage example

Accepts an array of <String|Object>'s. String entries are legacy supported. Use filename instead.

If importScripts item is object, there are 2 possible properties to set on this object:

entry: {

  main: __dirname + '/src/index.js',

  sw: __dirname + '/src/service-worker-entry.js'

},

output: {

  publicPath: '/my/public/path',

  chunkfileName: '[name].[<hash|chunkhash>].js'

},

plugins: [

  new SWPrecacheWebpackPlugin({

    filename: 'my-project-service-worker.js',

    importScripts: [

      

      

      

      

      'some-known-script-path.js',

 

      

      

      { filename: 'some-known-script-path.[hash].js' },

 

      

      

      

      { chunkName: 'sw' },

 

      

      

      

      { chunkName: 'my-named-chunk' },

 

      

      

      

      

      

      

      

      

    ]

  }),

]

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).

Or add setup section to devServer config, e.g.:

module.exports = {
    devServer: {
        setup: function (app) {
            app.get('/service-worker.js', function (req, res) {
                res.set({ 'Content-Type': 'application/javascript; charset=utf-8' });
                res.send(fs.readFileSync('build/service-worker.js'));
            });
        }
    }
}

There will likely never be webpack-dev-server support. sw-precache needs physical files in order to generate the service worker. webpack-dev-server files are in-memory. It is only possible to provide sw-precache with globs to find these files. It will follow the glob pattern and generate a list of file names to cache.

Contributing

Install node dependencies:

  $ npm install

Or:

  $ yarn

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

Testing

Tests are located in ./test

Run tests:

  $ npm t

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4