Search code examples
service-workerwebpack-4workbox

Generate ServiceWorker using workbox 6 - how to import "registerRoute" from "workbox-routing"?


I have upgraded my project to use workbox 6 and have modified my code accordingly. After injecting manifest (generating serviceWorker.js) my browser reports error:

Service worker error TypeError: ServiceWorker script at 
http://127.0.0.1:8080/serviceWorker.js for scope 
http://127.0.0.1:8080/ threw an exception during script evaluation. app.js:218:23

I have removed code to determine what causes the error and am now left with:

serviceWorker.js (generated from serviceWroker-base.js)

importScripts('workbox-sw.js');
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';

const CACHE_DYNAMIC_NAME = 'dynamic-DEBUG-001'

webpack.config.js

const {InjectManifest} = require('workbox-webpack-plugin')
const workboxWebpackInjectPlugin = new InjectManifest({
  swSrc: './serviceWorker.js'
})
// build WEBPACK CONFIG
const config = {}
//...
config.plugins = [
  nodeEnvPlugin,
  firebasePlugin,
  cssExtractPlugin,
  workboxWebpackInjectPlugin,
]
//...
return config

If I remove the imports of registerRoute and StaleWhileRevalidate in serviceWorker.js then the service worker registers successfully - but then I cannot register routes. ;) I have installed workbox-routing and workbox-strategies.

package.json

"scripts": {
  "generate:sw": "workbox injectManifest"
},
"dependencies": {
  ...
  "workbox-routing": "^6.0.2",
  "workbox-strategies": "^6.0.2"
},
"devDependencies": {
  ...
  "webpack": "^4.41.2"
}

generate:sw is the command I run to inject manifest and create serviceWorker.js.

My suspicion is that the imoprts are not handled correctly? How can I use registerRoute and StaleWhileRevalidate in my service worker?

Kind regards /K


Solution

  • The info at https://developers.google.com/web/tools/workbox/guides/using-bundlers might be helpful.

    You don't need to include importScripts('workbox-sw.js');

    If you plan on using precaching:

    • You can run InjectManifest via workbox-webpack-plugin and it will take care of both compiling your service worker (i.e. inlining the ES module imports into a final, runnable service worker file) as well as replacing a self.__WB_MANIFEST inside your service worker file with the actual precache manifest based on the assets in your webpack build.

    If you don't plan on using precaching:

    • You can add your service worker file, including the ES module imports, as a entry point in your webpack config, and that should handle inlining the ES module imports into a final, runnable service worker file.

    If you're already using webpack, then your workbox injectManifest step isn't needed. See the previous two points.