DEV Community

Divyansh Gupta
Divyansh Gupta

Posted on

Configuring Workbox with Create React App

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();
Enter fullscreen mode Exit fullscreen mode

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');
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

3 - Add the following to your scripts in package.json

"build-sw": "node ./src/sw-build.js",
Enter fullscreen mode Exit fullscreen mode

4 - Add npm run build-sw to your build script in package.json like this

"build": "react-scripts build && npm run build-sw",
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
mohammadazimi profile image
Mohammad Azimi

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

const variable = 'js variable';
// ~> no space between them ` ` `js
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ajsystem profile image
ajsystem

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

Collapse
 
bernardbaker profile image
Bernard Baker

Hi, let me know how you get on with that. And welcome to Dev.to 😄

Collapse
 
abhishek150190 profile image
Abhishek150190

Not Working