sw-precache-webpack-plugin
Webpack plugin that generates a service worker using sw-precache that will cache webpack's bundles' emitted assets. You can optionally pass sw-precache configuration options to webpack through this plugin.
Top Related Projects
📦 Workbox: JavaScript libraries for Progressive Web Apps
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
Quick Overview
The sw-precache-webpack-plugin
is a Webpack plugin that generates a service worker file using sw-precache. It integrates seamlessly with Webpack builds, allowing developers to easily add offline caching capabilities to their web applications. This plugin is particularly useful for creating Progressive Web Apps (PWAs) with offline functionality.
Pros
- Seamless integration with Webpack build process
- Automatically generates a service worker file
- Customizable caching strategies
- Supports dynamic content caching
Cons
- Deprecated in favor of Workbox
- Limited maintenance and updates
- May not support the latest service worker features
- Potential complexity for beginners
Code Examples
- Basic usage in webpack.config.js:
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
module.exports = {
// ... other webpack config
plugins: [
new SWPrecacheWebpackPlugin({
cacheId: 'my-project-name',
filename: 'service-worker.js',
staticFileGlobs: ['dist/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'],
minify: true,
}),
],
};
- Custom runtime caching:
new SWPrecacheWebpackPlugin({
// ... other options
runtimeCaching: [{
urlPattern: /^https:\/\/api\.example\.com\//,
handler: 'networkFirst'
}],
});
- Excluding specific files:
new SWPrecacheWebpackPlugin({
// ... other options
staticFileGlobs: ['dist/**/*.{js,html,css,png,jpg,gif}'],
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
});
Getting Started
-
Install the plugin:
npm install --save-dev sw-precache-webpack-plugin
-
Add the plugin to your webpack.config.js:
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); module.exports = { // ... other webpack config plugins: [ new SWPrecacheWebpackPlugin({ cacheId: 'my-project-name', filename: 'service-worker.js', staticFileGlobs: ['dist/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'], minify: true, }), ], };
-
Register the service worker in your main JavaScript file:
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js'); }
Competitor Comparisons
📦 Workbox: JavaScript libraries for Progressive Web Apps
Pros of Workbox
- More comprehensive and feature-rich service worker library
- Actively maintained by Google, ensuring regular updates and improvements
- Offers a modular approach, allowing developers to use only the features they need
Cons of Workbox
- Steeper learning curve due to its extensive feature set
- Potentially larger bundle size if not properly configured
Code Comparison
sw-precache-webpack-plugin:
new SWPrecacheWebpackPlugin({
cacheId: 'my-app-cache',
filename: 'service-worker.js',
staticFileGlobs: ['dist/**/*.{js,html,css,png,jpg,gif}'],
minify: true,
})
Workbox:
new WorkboxWebpackPlugin.GenerateSW({
clientsClaim: true,
skipWaiting: true,
runtimeCaching: [
{
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
handler: 'CacheFirst',
},
],
})
The sw-precache-webpack-plugin is simpler to set up but offers less flexibility. Workbox provides more advanced caching strategies and runtime caching options out of the box, allowing for finer control over service worker behavior. While sw-precache-webpack-plugin is easier to get started with, Workbox offers more powerful features for building robust Progressive Web Apps.
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
Pros of offline-plugin
- More comprehensive offline support, including AppCache fallback
- Flexible caching strategies with support for various service worker features
- Better integration with webpack, automatically detecting and caching emitted assets
Cons of offline-plugin
- Steeper learning curve due to more configuration options
- May require more setup for basic use cases compared to sw-precache-webpack-plugin
Code Comparison
sw-precache-webpack-plugin:
new SWPrecacheWebpackPlugin({
cacheId: 'my-app-cache',
filename: 'service-worker.js',
staticFileGlobs: ['dist/**/*.{js,html,css,png,jpg,gif}'],
minify: true,
})
offline-plugin:
new OfflinePlugin({
caches: {
main: ['index.html', 'app.js', 'app.css'],
additional: ['*.chunk.js']
},
ServiceWorker: {
events: true
},
AppCache: { events: true }
})
Both plugins aim to provide offline capabilities for webpack-built applications, but offline-plugin offers more advanced features and flexibility at the cost of increased complexity. sw-precache-webpack-plugin is simpler to set up for basic caching needs, while offline-plugin provides more control over caching strategies and supports a wider range of offline scenarios.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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/'; // webpack needs the trailing slash for output.publicPath
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:
filename
:[String]
- Service worker filename, default isservice-worker.js
filepath
:[String]
- Service worker path and name, default is to usewebpack.output.path
+options.filename
. This will overridefilename
. 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.
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:
cacheId
:[String]
- Not required but you should include this, it will give your service worker cache a unique name. Defaults to "sw-precache-webpack-plugin".importScripts
:[Array<String|Object>]
- When importScripts array item is a
String
:- Converts to object format
{ filename: '<publicPath>/my-script.js'}
- Converts to object format
- When importScripts array item is an
Object
:- Looks for
chunkName
property. - Looks for
filename
property. - If a
chunkName
is specified, it will override the accompanied value forfilename
.
- Looks for
- When importScripts array item is a
replacePrefix
:[String]
- Should only be used in conjunction withstripPrefix
runtimeCaching
:[Array<Object>]
- Configures runtime caching for dynamic content such as HTTP requests. Refer to sw-precache to see all available options.staticFileGlobs
:[Array<String>]
- Omit this to allow the plugin to cache all your bundles' emitted assets. IfmergeStaticsConfig=true
: this value will be merged with your bundles' emitted assets, otherwise this value is just passed tosw-precache
and emitted assets won't be included.stripPrefix
:[String]
- Same asstripPrefixMulti[stripPrefix] = ''
stripPrefixMulti
:[Object<String,String>]
- Omit this to use your webpack config'soutput.path + '/': output.publicPath
. IfmergeStaticsConfig=true
, this value will be merged with your webpack'soutput.path: publicPath
for stripping prefixes. Otherwise this property will be passed directly tosw-precache
and webpack's output path won't be replaced.
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/', // 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
}),
]
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).
/**
* @module {Object} webpack.config
*/
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
/** @constant {Object} Application entry points and bundle names */
const APPS = {
home: path.resolve(__dirname, 'src/home'),
posts: path.resolve(__dirname, 'src/posts'),
users: path.resolve(__dirname, 'src/users'),
}
/** @constant {string} build directory name */
const OUTPUT_DIR = 'dist';
/**
* @alias webpack.config
* @type {Object}
*/
module.exports = {
entry: APPS,
output: {
path: path.resolve(__dirname, OUTPUT_DIR),
filename: '[name].[hash].js',
},
plugins: [
// iterate over each `entry[app]` key.
...Object.keys(APPS)
.map(app => new SWPrecacheWebpackPlugin({
cacheId: `${app}`,
filename: `${app}-service-worker.js`,
stripPrefix: OUTPUT_DIR,
// We specify paths to the compiled destinations of resources for each "app's"
// bundled resources. This is one way to separate bundled assets for each
// application.
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:
- filename: Use this if you are referencing a path that "you just know" exists. You probably don't want to use this for named chunks.
- chunkName: Supports named entry chunks & dynamically imported named chunks.
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: [
// * legacy supported
// [chunkhash] is not supported for this usage
// This is transformed to new object syntax:
// { filename: '/my/public/path/some-known-script-path.js' }
'some-known-script-path.js',
// This use case is identical to above, except
// for excluding the .[hash] part:
{ filename: 'some-known-script-path.[hash].js' },
// When [chunkhash] is specified in filename:
// - filename must match the format specified in output.chunkfileName
// - If chunkName is invalid; an error will be reported
{ chunkName: 'sw' },
// Works for named entry chunks & dynamically imported named chunks:
// For ex, if in your code is:
// import(/* webpackChunkName: "my-named-chunk" */ './my-async-script.js');
{ chunkName: 'my-named-chunk' },
// All importScripts entries resolve to a string, therefore
// the final output of the above input is:
// [
// '/my/public/path/some-known-script-path.js',
// '/my/public/path/some-known-script-path.<compilation hash>.js',
// '/my/public/path/some-known-script-path.<chunkhash>.js',
// '/my/public/path/<id>.my-named-chunk.<chunkhash>.js'
// ]
]
}),
]
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
Top Related Projects
📦 Workbox: JavaScript libraries for Progressive Web Apps
Offline plugin (ServiceWorker, AppCache) for webpack (https://webpack.js.org/)
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot