Search code examples
javascriptreactjscreate-react-appworkbox

Workbox in Create React App without eject


I'm trying to configure Workbox in CRA without eject. Anyone succeeded?


Solution

  • After hours trialing and error I succeeded to have workbox in CRA. Here's how I did:

    First,yarn add -D workbox-build

    Next, create a file called build-sw.js in the root folder with:

    const fs = require('fs-extra');
    const pathmodule = require('path');
    const workbox = require('workbox-build');
    
    function build() {
      const cwd = process.cwd();
      const pkgPath = `${cwd}/node_modules/workbox-sw/package.json`;
      const pkg = require(pkgPath);
      const readPath = `${cwd}/node_modules/workbox-sw/${pkg.main}`;
      let data = fs.readFileSync(readPath, 'utf8');
      let path = `${cwd}/build/workbox-sw.js`;
      console.log(`Writing ${path}.`);
      fs.writeFileSync(path, data, 'utf8');
      data = fs.readFileSync(`${readPath}.map`, 'utf8');
      path = `${cwd}/build/${pathmodule.basename(pkg.main)}.map`;
      console.log(`Writing ${path}.`);
      fs.writeFileSync(path, data, 'utf8');
    
      workbox
        .injectManifest({
          globDirectory: 'build',
          globPatterns: ['**/*.{html,js,css,png,jpg,json}'],
          globIgnores: ['sw-default.js', 'service-worker.js', 'workbox-sw.js'],
          swSrc: './src/sw-template.js',
          swDest: 'build/sw-default.js'
        })
        .then(_ => {
          console.log('Service worker generated.');
        });
    }
    
    try {
      build();
    } catch (e) {
      console.log(e);
    }
    

    After that, create a file in src/sw-template.jswith: (Have in mind that in this file is where you have to put your own cache strategy. See Docs for more info)

    workbox.setConfig({
      debug: true
    });
    
    workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);
    
    workbox.precaching.precacheAndRoute([]);
    
    workbox.skipWaiting();
    workbox.clientsClaim();
    
    workbox.routing.registerRoute('/', workbox.strategies.networkFirst());
    

    Finally, in src/registerServiceWorker.js change:

    -      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
    +      const swUrl = `${process.env.PUBLIC_URL}/sw-default.js`;
    

    And in package.json change:

    -      "build": "react-scripts build && sw-precache --config=sw-precache-config.js'",
    +      "build": "react-scripts build && yarn sw",
    +      "sw": "node build-sw.js"
    

    Hope it helps!