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

generate-sw.mddocs/

Service Worker Generation

The GenerateSW plugin automatically generates a complete service worker file with precaching and runtime caching configuration. It analyzes your webpack build output and creates an optimized service worker for Progressive Web App caching strategies.

Capabilities

GenerateSW Class

Creates a webpack plugin that generates a complete service worker file during the build process.

/**
 * Creates an instance of GenerateSW plugin
 * @param config - Configuration options for service worker generation
 */
class GenerateSW {
  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 {
  manifestEntries?: Array<ManifestEntry>;
}

Usage Examples:

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

// Basic configuration
new GenerateSW({
  swDest: 'service-worker.js',
  skipWaiting: true,
  clientsClaim: true,
});

// Advanced configuration with runtime caching
new GenerateSW({
  swDest: 'sw.js',
  skipWaiting: true,
  clientsClaim: true,
  exclude: [/\.map$/, /manifest$/, /\.htaccess$/],
  maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, // 5MB
  runtimeCaching: [
    {
      urlPattern: /^https:\/\/fonts\.googleapis\.com/,
      handler: 'StaleWhileRevalidate',
      options: {
        cacheName: 'google-fonts-stylesheets',
      },
    },
    {
      urlPattern: /^https:\/\/api\.example\.com\/users/,
      handler: 'NetworkFirst',
      options: {
        cacheName: 'api-users',
        expiration: {
          maxEntries: 50,
          maxAgeSeconds: 300, // 5 minutes
        },
      },
    },
    {
      urlPattern: /\.(?:png|jpg|jpeg|svg|gif)$/,
      handler: 'CacheFirst',
      options: {
        cacheName: 'images',
        expiration: {
          maxEntries: 60,
          maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
        },
      },
    },
  ],
  navigateFallback: '/index.html',
  navigateFallbackDenylist: [/^\/api\//, /^\/admin\//],
});

Configuration Options

The GenerateSW plugin accepts all options from workbox-build's generateSW method, plus webpack-specific options.

interface WebpackGenerateSWOptions {
  /** Additional entries to include in the precache manifest */
  additionalManifestEntries?: Array<ManifestEntry | string>;
  
  /** Babel preset-env targets for service worker compilation */
  babelPresetEnvTargets?: string[];
  
  /** Cache ID prefix for all caches used by the service worker */
  cacheId?: string;
  
  /** Remove outdated caches during service worker activation */
  cleanupOutdatedCaches?: boolean;
  
  /** Service worker takes control of all clients immediately */
  clientsClaim?: boolean;
  
  /** Directory index file for navigation requests */
  directoryIndex?: string;
  
  /** Disable development logging in the generated service worker */
  disableDevLogs?: boolean;
  
  /** Files to exclude from precaching */
  exclude?: Array<RegExp | string | ((asset: {name: string}) => boolean)>;
  
  /** Webpack chunks to exclude from precaching */
  excludeChunks?: Array<string>;
  
  /** URL parameters to ignore when matching precached URLs */
  ignoreURLParametersMatching?: Array<RegExp>;
  
  /** Additional scripts to import into the service worker */
  importScripts?: Array<string>;
  
  /** Webpack chunks whose files should be imported into the service worker */
  importScriptsViaChunks?: Array<string>;
  
  /** Inline the Workbox runtime instead of importing it */
  inlineWorkboxRuntime?: boolean;
  
  /** Functions to transform the precache manifest */
  manifestTransforms?: Array<ManifestTransform>;
  
  /** Maximum file size (in bytes) to include in precache */
  maximumFileSizeToCacheInBytes?: number;
  
  /** Build mode - affects optimization and debugging */
  mode?: 'development' | 'production';
  
  /** URL to use for navigation fallback */
  navigateFallback?: string;
  
  /** URLs that should use navigation fallback */
  navigateFallbackAllowlist?: Array<RegExp>;
  
  /** URLs that should not use navigation fallback */
  navigateFallbackDenylist?: Array<RegExp>;
  
  /** Enable offline Google Analytics */
  offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions;
  
  /** Runtime caching strategies for different URL patterns */
  runtimeCaching?: Array<RuntimeCachingEntry>;
  
  /** Service worker skips waiting and activates immediately */
  skipWaiting?: boolean;
  
  /** Generate source maps for the service worker */
  sourcemap?: boolean;
  
  /** Output filename for the generated service worker */
  swDest?: string;
}

Runtime Caching Configuration

Configure caching strategies for different types of requests:

interface RuntimeCachingEntry {
  /** Caching strategy to use */
  handler: 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';
  
  /** Pattern to match URLs against */
  urlPattern: RegExp | string | ((params: {request: Request, url: URL}) => boolean);
  
  /** HTTP method to match (defaults to GET) */
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'PATCH';
  
  /** Additional options for the caching strategy */
  options?: {
    /** Background sync configuration */
    backgroundSync?: {
      name: string;
      options?: BackgroundSyncOptions;
    };
    
    /** Broadcast update configuration */
    broadcastUpdate?: {
      channelName?: string;
      options?: BroadcastChannelOptions;
    };
    
    /** Response caching criteria */
    cacheableResponse?: {
      statuses?: Array<number>;
      headers?: Record<string, string>;
    };
    
    /** Cache name for this strategy */
    cacheName?: string;
    
    /** Cache expiration settings */
    expiration?: {
      maxEntries?: number;
      maxAgeSeconds?: number;
    };
    
    /** Network timeout in seconds */
    networkTimeoutSeconds?: number;
    
    /** Workbox plugins to apply */
    plugins?: Array<any>;
    
    /** Fallback configuration for precached resources */
    precacheFallback?: {
      fallbackURL: string;
    };
  };
}

Common Runtime Caching Patterns:

// Cache Google Fonts
{
  urlPattern: /^https:\/\/fonts\.googleapis\.com/,
  handler: 'StaleWhileRevalidate',
  options: {
    cacheName: 'google-fonts-stylesheets',
  },
}

// Cache API responses with network priority
{
  urlPattern: /^https:\/\/api\.example\.com/,
  handler: 'NetworkFirst',
  options: {
    cacheName: 'api-cache',
    networkTimeoutSeconds: 3,
    expiration: {
      maxEntries: 50,
      maxAgeSeconds: 5 * 60, // 5 minutes
    },
  },
}

// Cache images with cache priority
{
  urlPattern: /\.(?:png|jpg|jpeg|svg|gif|webp)$/,
  handler: 'CacheFirst',
  options: {
    cacheName: 'images',
    expiration: {
      maxEntries: 100,
      maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
    },
  },
}

Install with Tessl CLI

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

docs

generate-sw.md

index.md

inject-manifest.md

tile.json