There are many ways to integrate Workbox in CRA, you can use a library like react-app-rewired or eject react-scripts for taking full control over your configuration for your web app. But we are going to use a small dev dependency called workbox-build for this.
1 - Add these 2 files to your src folder
sw-build.js
const workboxBuild = require('workbox-build');
// NOTE: This should be run *AFTER* all your assets are built
const buildSW = () => {
// This will return a Promise
workboxBuild
.injectManifest({
swSrc: 'src/sw-template.js', // this is your sw template file
swDest: 'build/service-worker.js', // this will be created in the build step
globDirectory: 'build',
globPatterns: ['**/*.{jpg}'], // precaching jpg files
})
.then(({ count, size, warnings }) => {
// Optionally, log any warnings and details.
warnings.forEach(console.warn);
console.log(`${count} files will be precached, totaling ${size} bytes.`);
})
.catch(console.error);
};
buildSW();
This file will run on every build and will inject your custom service worker from sw-template.js in place.
sw-template.js
if (typeof importScripts === 'function') {
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js');
/* global workbox */
if (workbox) {
console.log('Workbox is loaded');
workbox.core.skipWaiting();
/* injection point for manifest files. */
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);
/* custom cache rules */
workbox.routing.registerRoute(
new workbox.routing.NavigationRoute(
new workbox.strategies.NetworkFirst({
cacheName: 'PRODUCTION',
})
)
);
} else {
// console.log('Workbox could not be loaded. No Offline support');
}
}
This file is our custom service worker and uses Network first strategy. Read more about workbox caching strategies here.
You can try out caching fonts also using CacheFirst strategy.
2 - Install workbox-build
npm install --save-dev workbox-build
3 - Add the following to your scripts in package.json
"build-sw": "node ./src/sw-build.js",
4 - Add npm run build-sw to your build script in package.json like this
"build": "react-scripts build && npm run build-sw",
Finally in your index.js replace the serviceWorker.unregister() to serviceWorker.register()
And there we have it
We have successfully integrated workbox in our React APP. You can find the Github repo here.
Top comments (4)
Thank you for the article. and a suggestion. please add "js" after backquote. this will cause a better view of the code format in the article ๐ .
like this
Thanks dude, it's working great so far. Just need to adjust importScripts('storage.googleapis.com/workbox-cdn...); to match the actual dependency that was installed via npm
Hi, let me know how you get on with that. And welcome to Dev.to ๐
Not Working