Skip to content

Instantly share code, notes, and snippets.

@carlosalvarez91
Last active January 14, 2024 14:59
Show Gist options
  • Save carlosalvarez91/5d08756e8cbfa4471190853aec937c06 to your computer and use it in GitHub Desktop.
Save carlosalvarez91/5d08756e8cbfa4471190853aec937c06 to your computer and use it in GitHub Desktop.
customize service worker with workbox
//https://medium.com/@nrlhq/setting-up-pwa-lighthouse-audit-with-create-react-app-40e17180ea6b
// npm i react-app-rewired customize-cra workbox-webpack-plugin workbox-precaching
// this will generate a workbox.js file in /build
//no need for precache-manifest.12345blabla.js
const { override, addWebpackPlugin } = require('customize-cra');
const { InjectManifest } = require('workbox-webpack-plugin');
module.exports =(webpack, args)=> {
// remove GenerateSW plugin
webpack.plugins.pop();
const overridenConf = override(
addWebpackPlugin(
// injectManifest vs GenerateSW
//https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin
// new GenerateSW({
// swDest:'./workbox.js',
// exclude: [/\.(?:png|jpg|jpeg|svg)$/, /\.map$/, /manifest\.json$/, /workbox\.js$/, /sw\.js$/],
// })
new InjectManifest({
swSrc: './src/workbox.js'
}),
),
// ...other configs
// fixBabelImports('import', {
//}),
}),
)(webpack, ...args)
return overridenConf
}
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
//...
window.addEventListener('load', () => {
// const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
const swUrl = `${process.env.PUBLIC_URL}/workbox.js`;
//...
// src/workbox.js
/* eslint no-restricted-globals: "off" */
import {precacheAndRoute} from 'workbox-precaching';
console.log('Custom Service Worker');
precacheAndRoute(self.__WB_MANIFEST || []);
//..more service workers customizations here (I guess)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment