This module efficiently precaches assets for Progressive Web Apps and service workers.
—
High-level functions for quick precaching setup that handle the most common use cases. These functions provide an easy way to get started with precaching without needing to understand the underlying implementation details.
The most commonly used function that combines precaching assets and setting up request routing in a single call.
/**
* Adds items to the precache list and adds a route to respond to fetch events
* @param entries - Array of entries to precache (PrecacheEntry objects or URL strings)
* @param options - Optional route configuration options
*/
function precacheAndRoute(
entries: Array<PrecacheEntry | string>,
options?: PrecacheRouteOptions
): void;Usage Examples:
import { precacheAndRoute } from "workbox-precaching";
// Basic usage with mixed entry types
precacheAndRoute([
// PrecacheEntry with revision for cache busting
{ url: "/index.html", revision: "abc123" },
{ url: "/styles.css", revision: "def456" },
// String URLs (use URL as cache key)
"/static/logo.png",
"/api/data.json",
// Entry with integrity for security
{
url: "/critical.js",
revision: "xyz789",
integrity: "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
}
]);
// With route options
precacheAndRoute([
{ url: "/app.html", revision: "v1.2.3" }
], {
// Serve /app.html for directory requests like /dashboard/
directoryIndex: "app.html",
// Ignore tracking parameters when matching URLs
ignoreURLParametersMatching: [/^utm_/, /^fbclid$/],
// Try .html extension for clean URLs
cleanURLs: true
});Adds items to the precache list for installation during the service worker install event. Does not set up request routing.
/**
* Adds items to the precache list and stores them during service worker install.
* Note: Only precaches files - does not serve them. Use addRoute() to serve cached files.
* @param entries - Array of entries to precache (PrecacheEntry objects or URL strings)
*/
function precache(entries: Array<PrecacheEntry | string>): void;Usage Examples:
import { precache, addRoute } from "workbox-precaching";
// Precache assets without setting up routing
precache([
"/offline.html",
"/fallback.css",
{ url: "/app-shell.html", revision: "v2.1.0" }
]);
// Later, set up routing separately
addRoute({
cleanURLs: true,
directoryIndex: "app-shell.html"
});Adds a fetch event listener to the service worker that responds to network requests with precached assets.
/**
* Adds a fetch listener to the service worker that responds to network requests with precached assets.
* Must be called after precache() to serve the precached resources.
* @param options - Optional configuration options for the precache route
*/
function addRoute(options?: PrecacheRouteOptions): void;Usage Examples:
import { precache, addRoute } from "workbox-precaching";
// First, precache the assets
precache([
"/index.html",
"/about.html",
"/contact.html"
]);
// Then add routing with custom options
addRoute({
// Custom directory index
directoryIndex: "index.html",
// Ignore search parameters
ignoreURLParametersMatching: [/^ref$/, /^campaign$/],
// Enable clean URLs (serve /about.html for /about)
cleanURLs: true,
// Custom URL manipulation for additional URL variants
urlManipulation: ({ url }) => {
// Also try with trailing slash
if (!url.pathname.endsWith('/')) {
const newUrl = new URL(url);
newUrl.pathname += '/';
return [newUrl];
}
return [];
}
});interface PrecacheRouteOptions {
/** Default file for directory requests (default: 'index.html') */
directoryIndex?: string;
/** URL parameters to ignore when matching (default: [/^utm_/, /^fbclid$/]) */
ignoreURLParametersMatching?: RegExp[];
/** Whether to try .html extension for clean URLs (default: true) */
cleanURLs?: boolean;
/** Custom URL manipulation function for generating additional URL variations */
urlManipulation?: urlManipulation;
}
/**
* Callback function for generating additional URL variations to check against precached files
* @param context - Object containing the request URL
* @returns Array of additional URLs to check (should be URL objects, not strings)
*/
type urlManipulation = ({ url }: { url: URL }) => URL[];interface PrecacheEntry {
/** URL to precache */
url: string;
/** Revision information for cache busting (if null, uses URL as cache key) */
revision?: string | null;
/** Integrity metadata for network request validation */
integrity?: string;
}Most build tools generate a manifest of assets with revisions:
import { precacheAndRoute } from "workbox-precaching";
// Usually generated by build tools like Workbox CLI or webpack plugin
const precacheManifest = [
{ url: "/index.html", revision: "a1b2c3" },
{ url: "/styles.css", revision: "d4e5f6" },
{ url: "/script.js", revision: "g7h8i9" }
];
precacheAndRoute(precacheManifest);Combine generated and static assets:
import { precacheAndRoute } from "workbox-precaching";
precacheAndRoute([
// Generated assets with revisions
...self.__WB_MANIFEST,
// Static assets (use URL as cache key)
"/images/logo.png",
"/fonts/custom.woff2"
]);Install with Tessl CLI
npx tessl i tessl/npm-workbox-precaching