CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-workbox-webpack-plugin

A plugin for your Webpack build process, helping you generate a manifest of local files that workbox-sw should precache.

Overall
score

80%

Overview
Eval results
Files

index.mddocs/

Workbox Webpack Plugin

Workbox Webpack Plugin provides Webpack plugins that integrate Workbox functionality into Webpack builds, enabling automatic generation of service worker precache manifests and configurations. It helps developers implement Progressive Web App (PWA) caching strategies by automatically analyzing build outputs and generating optimized precache lists for static assets.

Package Information

  • Package Name: workbox-webpack-plugin
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install workbox-webpack-plugin

Core Imports

import { GenerateSW, GenerateSWConfig, InjectManifest } from "workbox-webpack-plugin";

For CommonJS:

const { GenerateSW, GenerateSWConfig, InjectManifest } = require("workbox-webpack-plugin");

Default export (for backward compatibility):

import WorkboxPlugin from "workbox-webpack-plugin";
const { GenerateSW, InjectManifest } = WorkboxPlugin;

Basic Usage

import { GenerateSW, InjectManifest } from "workbox-webpack-plugin";

// Generate complete service worker
module.exports = {
  // ... webpack config
  plugins: [
    new GenerateSW({
      swDest: 'sw.js',
      skipWaiting: true,
      clientsClaim: true,
      runtimeCaching: [{
        urlPattern: /^https:\/\/api\.example\.com/,
        handler: 'NetworkFirst',
        options: {
          cacheName: 'api-cache',
        },
      }],
    }),
  ],
};

// Inject manifest into existing service worker
module.exports = {
  // ... webpack config
  plugins: [
    new InjectManifest({
      swSrc: './src/sw.js',
      swDest: 'sw.js',
    }),
  ],
};

Architecture

Workbox Webpack Plugin consists of two main components:

  • GenerateSW Plugin: Automatically generates a complete service worker file with precaching and runtime caching configuration
  • InjectManifest Plugin: Takes an existing service worker and injects a precache manifest based on webpack assets
  • Asset Analysis: Automatically discovers and processes webpack compilation assets to create precache manifests
  • Webpack Integration: Hooks into webpack's compilation process using appropriate lifecycle events for v4/v5 compatibility

Capabilities

Service Worker Generation

Complete service worker generation with automatic precaching and customizable runtime caching strategies.

class GenerateSW {
  /**
   * Creates an instance of GenerateSW plugin
   * @param config - Configuration options for service worker generation
   */
  constructor(config?: GenerateSWConfig);
  
  /**
   * Webpack plugin interface method - called by webpack during compilation
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: webpack.Compiler): void;
}

interface GenerateSWConfig extends WebpackGenerateSWOptions {
  /** Optional array of additional manifest entries to include in precache */
  manifestEntries?: Array<ManifestEntry>;
}

Service Worker Generation

Manifest Injection

Inject precache manifest into existing service worker source files with webpack compilation support.

class InjectManifest {
  /**
   * Creates an instance of InjectManifest plugin
   * @param config - Configuration options for manifest injection
   */
  constructor(config: WebpackInjectManifestOptions);
  
  /**
   * Webpack plugin interface method - called by webpack during compilation
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: webpack.Compiler): void;
}

Manifest Injection

Types

interface ManifestEntry {
  /** The URL of the asset to precache */
  url: string;
  /** The revision hash for cache busting, or null for unversioned assets */
  revision: string | null;
}

interface WebpackGenerateSWOptions {
  additionalManifestEntries?: Array<ManifestEntry | string>;
  babelPresetEnvTargets?: string[];
  cacheId?: string;
  cleanupOutdatedCaches?: boolean;
  clientsClaim?: boolean;
  directoryIndex?: string;
  disableDevLogs?: boolean;
  exclude?: Array<RegExp | string | ((asset: {name: string}) => boolean)>;
  excludeChunks?: Array<string>;
  ignoreURLParametersMatching?: Array<RegExp>;
  importScripts?: Array<string>;
  importScriptsViaChunks?: Array<string>;
  inlineWorkboxRuntime?: boolean;
  manifestTransforms?: Array<ManifestTransform>;
  maximumFileSizeToCacheInBytes?: number;
  mode?: 'development' | 'production';
  navigateFallback?: string;
  navigateFallbackAllowlist?: Array<RegExp>;
  navigateFallbackDenylist?: Array<RegExp>;
  offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions;
  runtimeCaching?: Array<RuntimeCachingEntry>;
  skipWaiting?: boolean;
  sourcemap?: boolean;
  swDest?: string;
}

interface WebpackInjectManifestOptions {
  additionalManifestEntries?: Array<ManifestEntry | string>;
  compileSrc?: boolean;
  exclude?: Array<RegExp | string | ((asset: {name: string}) => boolean)>;
  excludeChunks?: Array<string>;
  ignoreURLParametersMatching?: Array<RegExp>;
  injectionPoint?: string;
  manifestTransforms?: Array<ManifestTransform>;
  maximumFileSizeToCacheInBytes?: number;
  mode?: 'development' | 'production';
  swDest?: string;
  swSrc: string;
  webpackCompilationPlugins?: Array<any>;
}

interface RuntimeCachingEntry {
  handler: 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';
  urlPattern: RegExp | string | ((params: {request: Request, url: URL}) => boolean);
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'PATCH';
  options?: {
    backgroundSync?: {
      name: string;
      options?: BackgroundSyncOptions;
    };
    broadcastUpdate?: {
      channelName?: string;
      options?: BroadcastChannelOptions;
    };
    cacheableResponse?: {
      statuses?: Array<number>;
      headers?: Record<string, string>;
    };
    cacheName?: string;
    expiration?: {
      maxEntries?: number;
      maxAgeSeconds?: number;
    };
    networkTimeoutSeconds?: number;
    plugins?: Array<any>;
    precacheFallback?: {
      fallbackURL: string;
    };
  };
}

interface ManifestTransform {
  (originalManifest: Array<ManifestEntry>, compilation?: webpack.Compilation): Promise<{
    manifest: Array<ManifestEntry>;
    warnings?: Array<string>;
  }> | {
    manifest: Array<ManifestEntry>;
    warnings?: Array<string>;
  };
}

Install with Tessl CLI

npx tessl i tessl/npm-workbox-webpack-plugin

docs

generate-sw.md

index.md

inject-manifest.md

tile.json