Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a service worker using Webpack 5?

Tags:

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?

like image 602
Richard Hunter Avatar asked Oct 27 '20 06:10

Richard Hunter


2 Answers

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.

like image 171
pfg Avatar answered Sep 29 '22 09:09

pfg


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.

like image 43
Chris Weber Avatar answered Sep 29 '22 09:09

Chris Weber