Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

sw-precache

> 编程语言
Open source

[Deprecated] A node module to generate service worker code that will precache specific resources so they work offline.

5.2K stars0 likes2 views
WebsiteGitHub

About

[Deprecated] A node module to generate service worker code that will precache specific resources so they work offline.

⚠️ sw-precache ⚠️

sw-toolbox and sw-precache are deprecated in favor of Workbox. Please read this migration guide for information on upgrading.

About

Service Worker Precache is a module for generating a service worker that precaches resources. It integrates with your build process. Once configured, it detects all your static resources (HTML, JavaScript, CSS, images, etc.) and generates a hash of each file's contents. Information about each file's URL and versioned hash are stored in the generated service worker file, along with logic to serve those files cache-first, and automatically keep those files up to date when changes are detected in subsequent builds.

Serving your local static resources cache-first means that you can get all the crucial scaffolding for your web app—your App Shell—on the screen without having to wait for any network responses.

The module can be used in JavaScript-based build scripts, like those written with gulp, and it also provides a command-line interface. You can use the module directly, or if you'd prefer, use one of the wrappers around sw-precache for specific build environments, like webpack.

It can be used alongside the sw-toolbox library, which works well when following the App Shell + dynamic content model.

The full documentation is in this README, and the getting started guide provides a quicker jumping off point.

To learn more about the internals of the generated service worker, you can read this deep-dive by Huang Xuan.

Table of Contents

  • Install
  • Usage
    • Overview
    • Example
    • Considerations
    • Command-line interface
  • Runtime Caching
  • API
    • Methods
      • generate(options, callback)
      • write(filePath, options, callback)
    • Options Parameter
      • cacheId [String]
      • clientsClaim [Boolean]
      • directoryIndex [String]
      • dontCacheBustUrlsMatching [Regex]
      • dynamicUrlToDependencies [Object⟨String,Buffer,Array⟨String⟩⟩]
      • handleFetch [boolean]
      • ignoreUrlParametersMatching [Array⟨Regex⟩]
      • importScripts [Array⟨String⟩]
      • logger [function]
      • maximumFileSizeToCacheInBytes [Number]
      • navigateFallback [String]
      • navigateFallbackWhitelist [Array⟨RegExp⟩]
      • replacePrefix [String]
      • runtimeCaching [Array⟨Object⟩]
      • skipWaiting [Boolean]
      • staticFileGlobs [Array⟨String⟩]
      • stripPrefix [String]
      • stripPrefixMulti [Object]
      • templateFilePath [String]
      • verbose [boolean]
  • Wrappers and Starter Kits
    • CLIs
    • Starter Kits
    • Recipes for writing a custom wrapper
  • Acknowledgements
  • Support
  • License

Install

Local build integration:

$ npm install --save-dev sw-precache

Global command-line interface:

$ npm install --global sw-precache

Usage

Overview

  1. Make sure your site is served using HTTPS! Service worker functionality is only available on pages that are accessed via HTTPS. (http://localhost will also work, to facilitate testing.) The rationale for this restriction is outlined in the "Prefer Secure Origins For Powerful New Features" document.

  2. Incorporate sw-precache into your node-based build script. It should work well with either gulp or Grunt, or other build scripts that run on node. In fact, we've provided examples of both in the demo/ directory. Each build script in demo has a function called writeServiceWorkerFile() that shows how to use the API. Both scripts generate fully-functional JavaScript code that takes care of precaching and fetching all the resources your site needs to function offline. There is also a command-line interface available, for those using alternate build setups.

  3. Register the service worker JavaScript. The JavaScript that's generated needs to be registered as the controlling service worker for your pages. This technically only needs to be done from within a top-level "entry" page for your site, since the registration includes a scope which will apply to all pages underneath your top-level page. service-worker-registration.js is a sample script that illustrates the best practices for registering the generated service worker and handling the various lifecycle events.

Example

The project's sample gulpfile.js illustrates the full use of sw-precache in context. (Note that the sample gulpfile.js is the one in the demo folder, not the one in the root of the project.) You can run the sample by cloning this repo, using npm install to pull in the dependencies, changing to the demo/ directory, running `npm bin`/gulp serve-dist, and then visiting http://localhost:3000.

There's also a sample Gruntfile.js that shows service worker generation in Grunt. Though, it doesn't run a server on localhost.

Here's a simpler gulp example for a basic use case. It assumes your site's resources are located under app and that you'd like to cache all your JavaScript, HTML, CSS, and image files.

gulp.task('generate-service-worker', function(callback) {
  var swPrecache = require('sw-precache');
  var rootDir = 'app';

  swPrecache.write(`${rootDir}/service-worker.js`, {
    staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif,svg,eot,ttf,woff}'],
    stripPrefix: rootDir
  }, callback);
});

This task will create app/service-worker.js, which your client pages need to register before it can take control of your site's pages. service-worker-registration.js is a ready-to- use script to handle registration.

Considerations

  • Service worker caching should be considered a progressive enhancement. If you follow the model of conditionally registering a service worker only if it's supported (determined by if('serviceWorker' in navigator)), you'll get offline support on browsers with service workers and on browsers that don't support service workers, the offline-specific code will never be called. There's no overhead/breakage for older browsers if you add sw-precache to your build.

  • All resources that are precached will be fetched by a service worker running in a separate thread as soon as the service worker is installed. You should be judicious in what you list in the dynamicUrlToDependencies and staticFileGlobs options, since listing files that are non-essential (large images that are not shown on every page, for instance) will result in browsers downloading more data than is strictly necessary.

  • Precaching doesn't make sense for all types of resources (see the previous point). Other caching strategies, like those outlined in the Offline Cookbook, can be used in conjunction with sw-precache to provide the best experience for your users. If you do implement additional caching logic, put the code in a separate JavaScript file and include it using the importScripts() method.

  • sw-precache uses a cache-first strategy, which results in a copy of any cached content being returned without consulting the network. A useful pattern to adopt with this strategy is to display a toast/alert to your users when there's new content available, and give them an opportunity to reload the page to pick up that new content (which the service worker will have added to the cache, and will be available at the next page load). The sample service-worker-registration.js file illustrates the service worker lifecycle event you can listen for to trigger this message.

Command-line interface

For those who would prefer not to use sw-precache as part of a gulp or Grunt build, there's a command-line interface which supports the options listed in the API, provided via flags or an external JavaScript configuration file.

Hypenated flags are converted to camelCase options.
Options starting with --no prefix negate the boolean value. For example, --no-clients-claim sets the value of clientsClaim to false.

Warning: When using sw-precache "by hand", outside of an automated build process, it's your responsibility to re-run the command each time there's a change to any local resources! If sw-precache is not run again, the previously cached local resources will be reused indefinitely.

Sensible defaults are assumed for options that are not provided. For example, if you are inside the top-level directory that contains your site's contents, and you'd like to generate a service-worker.js file that will automatically precache all of the local files, you can simply run

$ sw-precache

Alternatively, if you'd like to only precache .html files that live within dist/, which is a subdirectory of the current directory, you could run

$ sw-precache --root=dist --static-file-globs='dist/**/*.html'

Note: Be sure to use quotes around parameter values that have special meanings to your shell (such as the * characters in the sample command line above, for example).

Finally, there's support for passing complex configurations using --config <file>. Any of the options from the file can be overridden via a command-line flag. We strongly recommend passing it an external JavaScript file defining config via module.exports. For example, assume there's a path/to/sw-precache-config.js file that contains:

module.exports = {
  staticFileGlobs: [
    'app/css/**.css',
    'app/**.html',
    'app/images/**.*',
    'app/js/**.js'
  ],
  stripPrefix: 'app/',
  runtimeCaching: [{
    urlPattern: /this\\.is\\.a\\.regex/,
    handler: 'networkFirst'
  }]
};

That file could be passed to the command-line

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScriptjavascriptofflineoffline-firstprogressive-web-app

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言