I'm using Webpack 5 and I want to have a Service Worker that will intercept fetch requests and return responses locally without hitting the network. I also want to be able to import npm modules within the Service Worker. I used to use a library called serviceworker-webpack-plugin for this purpose, but it's no longer maintained, (and throws errors when I use it). The Webpack docs recommend using Workbox, but this seems to be just for caching assets in the Service Worker, as far as I can gather. Could someone tell me what the correct approach is in 2020 for creating a Service Worker with Webpack 5?
Add the service worker to your webpack.config.js entries field
entry: {
'app': "./src/index.js",
'service-worker': "./src/service-worker.ts",
},
output: {
filename: "[name].js",
},
This will emit dist/app.js
and dist/service-worker.js
, and it will be possible to import things in both.
serviceworker-webpack-plugin
also provides a way for the serviceworker to see a list of all the bundle files it should cache, but that functionality is not available directly and requires making a webpack plugin to get.
2022 Answer
This is supported in webpack pretty much out of the box.
https://webpack.js.org/guides/progressive-web-application/
This will give you basic caching of assets which web pack is handling for your.
You can get more advanced: https://developer.chrome.com/docs/workbox/modules/workbox-webpack-plugin/
Note this is using Workbox from google. I've used this for years in an offline first app and it works very well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With