Workbox in Create React App without eject
Asked Answered
H

2

5

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

Hanzelin answered 26/7, 2018 at 7:45 Comment(0)
H
7

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!

Hanzelin answered 26/7, 2018 at 7:45 Comment(2)
Thanks so much for posting the answer to your own question. This has helped me a lot. I needed to remove the single quote after yarn sw in the final package.json step to make it work.Coupe
from where workbox is defined src/sw-template.js file?Summand
W
5

With the merge of this PR, Create React App 2 now support supports Workbox out of the box, since it now uses workbox-webpack-plugins internally.

Take a look at the official docs to learn more: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

Woolfolk answered 23/11, 2018 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.