Workbox in Create React App without eject

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

Upvotes: 5

Views: 1917

Answers (2)

kaushalyap
kaushalyap

Reputation: 13627

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

Upvotes: 5

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!

Upvotes: 7

Related Questions