offline-plugin

raw JSON →
5.0.7 verified Sat Apr 25 auth: no javascript maintenance

A webpack plugin that generates a ServiceWorker and optionally AppCache to make webpack projects work offline. Current stable version is 5.0.7 (latest release 2020-08-05). It caches all webpack output assets automatically, with options to customize caching, appShell, navigationPreload, and more. Compared to Workbox, it is simpler to set up but less flexible and has a slower release cadence (last stable release over 4 years ago).

error Error: OfflinePlugin is not a constructor
cause Improper import style: using require('offline-plugin').default or destructuring.
fix
Use const OfflinePlugin = require('offline-plugin') (CJS) or import OfflinePlugin from 'offline-plugin' (ESM).
error Cannot find module 'offline-plugin/runtime'
cause Missing runtime file or incorrect import path.
fix
Install offline-plugin as a dependency (not devDependency) and use import * as OfflinePluginRuntime from 'offline-plugin/runtime'.
error ServiceWorker registration failed: InvalidStateError
cause ServiceWorker script URL is not served with correct MIME type or is blocked by CSP.
fix
Ensure the service worker file is served with text/javascript MIME type and CSP allows worker-src.
breaking AppCache is now disabled by default. To enable it, set AppCache: true.
fix Add AppCache: true to plugin options if you need AppCache fallback.
breaking Support for webpack 1 and Node 4 dropped.
fix Upgrade to webpack 2+ and Node 6+.
deprecated ServiceWorker.navigateFallbackURL and navigateFallbackForRedirects removed; use appShell option instead.
fix Use appShell: '/shell' to define fallback for navigations.
gotcha If using terser-webpack-plugin, ensure offline-plugin is compatible; fixed in v5.0.7.
fix Upgrade to v5.0.7 or later.
gotcha Runtime must be installed on every page that needs offline support. One install per page is enough.
fix Call OfflinePluginRuntime.install() in your app's entry point.
npm install offline-plugin
yarn add offline-plugin
pnpm add offline-plugin

Configures OfflinePlugin in webpack and installs the runtime to activate ServiceWorker caching.

// webpack.config.js
import OfflinePlugin from 'offline-plugin';

export default {
  plugins: [
    new OfflinePlugin({
      appShell: '/index.html',
      caches: {
        main: ['app.*.js', 'vendor.*.js', 'styles.*.css'],
        additional: ['*.png', '*.svg', '*.jpg'],
        optional: [':rest:']
      },
      ServiceWorker: {
        events: true,
        navigateFallbackURL: '/'
      },
      AppCache: false
    })
  ]
};

// client.js (e.g. entry point)
import * as OfflinePluginRuntime from 'offline-plugin/runtime';
OfflinePluginRuntime.install();