Registry / devops / workbox-build

workbox-build

JSON →
library7.4.0jsnpmunverified

Workbox-build is a core module within the Workbox library, designed to integrate seamlessly into JavaScript build processes to facilitate the generation of precache manifests for service workers. Currently at version 7.4.0, this package focuses on the programmatic creation of a list of URLs and their revision details, which `workbox-sw` can then use to precache assets, enabling offline capabilities for web applications. Releases in the 7.x series have primarily focused on critical dependency updates and maintaining compatibility, with v7.0.0 notably raising the minimum Node.js requirement to version 16, and the latest versions further increasing it to Node.js >=20.0.0. It offers functions like `generateSW` for a complete service worker lifecycle management and `injectManifest` for greater customization, distinguishing itself by providing a robust, opinionated, yet flexible way to manage asset caching without direct reliance on specific bundlers, unlike `workbox-webpack-plugin` which is specifically for Webpack. Its steady release cadence primarily addresses security and dependency maintenance.

npm install workbox-build
INSTALL
IMPORT
SIG · WORKBOX-BUILD
W
workbox-build
devopsjavascriptv7.4.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

generateSW
import { generateSW } from 'workbox-build';
const { generateSW } = require('workbox-build');
Workbox primarily uses ESM for its build tools since Node.js 16+. While CommonJS might work in some older Node environments, ESM is the recommended and best-supported pattern.
injectManifest
import { injectManifest } from 'workbox-build';
const injectManifest = require('workbox-build').injectManifest;
`injectManifest` is used when you need more control over your service worker, allowing you to provide your own service worker file as a source. Ensure your Node.js project is configured for ESM.
getManifest
import { getManifest } from 'workbox-build';
import workboxBuild from 'workbox-build'; workboxBuild.getManifest();
`getManifest` returns the precache manifest without generating a full service worker. It's a named export, not part of a default export.

This quickstart demonstrates how to use `workbox-build`'s `generateSW` function to create a production-ready service worker. It configures precaching for common static assets and sets up a runtime caching strategy for Google Fonts, suitable for a PWA.

import { generateSW } from 'workbox-build'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const buildSW = async () => { try { const { count, size, warnings } = await generateSW({ swDest: path.join(__dirname, '..', 'dist', 'sw.js'), globDirectory: path.join(__dirname, '..', 'dist'), globPatterns: [ '**/*.{html,js,css,png,jpg,gif,svg,json,webmanifest,woff2}' ], ignoreURLParametersMatching: [/^utm_/, /^fbclid$/], skipWaiting: true, clientsClaim: true, runtimeCaching: [{ urlPattern: /^https:\/\/fonts\.googleapis\.com/, handler: 'StaleWhileRevalidate', options: { cacheName: 'google-fonts-stylesheets', }, },{ urlPattern: /^https:\/\/fonts\.gstatic\.com/, handler: 'CacheFirst', options: { cacheName: 'google-fonts-webfonts', cacheExpiration: { maxEntries: 30, maxAgeSeconds: 60 * 60 * 24 * 365, }, }, }], }); if (warnings.length > 0) { console.warn('Workbox build warnings:', warnings.join('\n')); } console.log(`Generated a service worker that will precache ${count} files, totaling ${size} bytes.`); } catch (error) { console.error('Workbox service worker generation failed:', error); process.exit(1); } }; buildSW();
Debug
Known issues
breakingThe minimum required Node.js version was updated to Node.js 16 with Workbox v7.0.0. Subsequently, the `engines` field in `workbox-build@7.4.0` specifies `>=20.0.0`, indicating another significant bump.
fix
Ensure your build environment uses Node.js version 20 or higher. Update your Node.js runtime and CI/CD configurations accordingly.
affects: >=7.0.0
gotchaWorkbox-build packages primarily use ESM (ECMAScript Modules). Using `require()` statements in a pure ESM Node.js project or in a context expecting ESM will lead to errors.
fix
Always use `import` statements for `workbox-build` and ensure your Node.js project is configured for ESM (e.g., `"type": "module"` in `package.json` or `.mjs` file extension).
affects: >=3.x
deprecatedEarlier versions of `workbox-build` (v6.4.1) addressed a security issue in a transitive dependency, `@apideck/better-ajv-errors`. While fixed, relying on older versions could expose applications to vulnerabilities.
fix
Always keep `workbox-build` updated to the latest stable version to receive critical security patches and dependency updates.
affects: <6.4.1
gotchaWhen using `generateSW` or `injectManifest`, incorrect configuration options (e.g., `globDirectory` not pointing to a valid directory, `swDest` being outside the `globDirectory` or an invalid path) can lead to silent failures or unexpected service worker behavior.
fix
Carefully review the Workbox documentation for each configuration option. Use absolute paths for `globDirectory` and `swDest`, and ensure the `globPatterns` correctly match your assets. Enable Workbox's verbose logging for debugging during development.
affects: >=1.0.0
Errors
Common errors & fixes
SyntaxError: Cannot use import statement outside a module
Attempting to use ES module `import` syntax in a CommonJS context (e.g., a `.js` file without `"type": "module"` in `package.json`, or an environment expecting CJS).
fix
Ensure your Node.js script file uses the `.mjs` extension or add `"type": "module"` to your `package.json`. If using older Node.js versions that don't fully support ESM, consider transpilation or updating Node.js.
TypeError: config.globDirectory must be a string
The `globDirectory` option, which specifies the base directory for globbing, was not provided or was provided with an incorrect type.
fix
Ensure `globDirectory` is set to a string representing an absolute path to the root of your web app's static assets, e.g., `path.join(__dirname, 'dist')`.
Error: It's an error to call generateSW() with the same swDest multiple times.
The `generateSW` function was invoked multiple times in a single build process attempting to write to the same `swDest` file, which is not supported.
fix
Ensure `generateSW` is called only once per build. If you have multiple parts of your build process that need a service worker, consolidate them or use `injectManifest` with a pre-existing service worker file.
Upgrade
Version history
7.4.0latest on npm
Audit
Dependencies
noderequiredRuntime environment. Minimum required version increased to >=20.0.0 in Workbox v7.4.0.
@apideck/better-ajv-errorsrequiredUsed for configuration validation and addresses security concerns in its dependencies. Critical dependency updates are a recurring theme in recent releases.
Agent activity
22 hits · last 30 days
node
20
OpenAI (training)
1
Resources