|
| 1 | +## ServiceWorkerPlugin |
| 2 | + |
| 3 | +Webpack plugin for configuring a ServiceWorker for different PWA development |
| 4 | +scenarios. |
| 5 | + |
| 6 | +### Usage |
| 7 | + |
| 8 | +In `webpack.config.js`: |
| 9 | + |
| 10 | +```js |
| 11 | +const path = require('path'); |
| 12 | +const buildpack = require('@magento/pwa-buildpack'); |
| 13 | +const ServiceWorkerPlugin = buildpack.Webpack.ServiceWorkerPlugin; |
| 14 | + |
| 15 | +module.exports = async env => { |
| 16 | + const config = { |
| 17 | + /* webpack config, i.e. entry, output, etc. */ |
| 18 | + plugins: [ |
| 19 | + /* other plugins */ |
| 20 | + new ServiceWorkerPlugin({ |
| 21 | + env: { |
| 22 | + mode: 'development' |
| 23 | + }, |
| 24 | + |
| 25 | + paths: { |
| 26 | + output: path.resolve(__dirname, 'web/js'), |
| 27 | + assets: path.resolve(__dirname, 'web') |
| 28 | + }, |
| 29 | + enableServiceWorkerDebugging: true, |
| 30 | + serviceWorkerFileName: 'sw.js', |
| 31 | + runtimeCacheAssetPath: 'https://cdn.url' |
| 32 | + }) |
| 33 | + ] |
| 34 | + }; |
| 35 | + |
| 36 | + return config; |
| 37 | + |
| 38 | +}; |
| 39 | +``` |
| 40 | + |
| 41 | +### Purpose |
| 42 | + |
| 43 | +This plugin is a wrapper around the [Google Workbox Webpack Plugin](https://developers.google.com/web/tools/workbox/guides/generate-service-worker/), |
| 44 | +which generates a caching ServiceWorker based on assets emitted by Webpack. |
| 45 | + |
| 46 | +In development, ServiceWorkers can cache assets in a way that interferes with |
| 47 | +real-time editing and changes. This plugin takes configuration that can switch |
| 48 | +between "normal development mode", where ServiceWorker is disabled, to "service |
| 49 | +worker debugging mode", where ServiceWorker is enabled and hot-reloading. |
| 50 | + |
| 51 | +### API |
| 52 | + |
| 53 | + |
| 54 | +#### `new ServiceWorkerPlugin(options: PluginOptions): Plugin` |
| 55 | + |
| 56 | +#### `options` |
| 57 | + |
| 58 | + - `env: object`: **Required.** An object representing the current environment. |
| 59 | + - `mode: string`: **Required**. Must be `'development'` or `'production'`. |
| 60 | + - `paths: object`: **Required.** Local absolute paths to theme folders. |
| 61 | + - `assets: string`: Directory for public static assets. |
| 62 | + - `enableServiceWorkerDebugging: boolean`: When `true`, the ServiceWorker will |
| 63 | + be active at document root (irrespective of publicPath) and hot reloading. |
| 64 | + When `false`, ServiceWorker will be disabled so that asset hot reloading is |
| 65 | + not interrupted by cache. |
| 66 | + - `serviceWorkerFileName: string`: **Required.** The name of the ServiceWorker |
| 67 | + file this theme creates, e.g. `'sw.js'`. |
| 68 | + - `runtimeCacheAssetPath: string`: **Required.** A path, or remote URL, |
| 69 | + representing the root path of assets which the ServiceWorker should cache at |
| 70 | + runtime as they are requested. |
0 commit comments