question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Guidlines for Using Workbox

See original GitHub issue

I am on React-Scripts 2.0.5. I am eager to use the new Workbox functionality that is mentioned in the release notes for 2.0. I can’t find any directions on how to do it though.

There are posts on Medium, Freecodecamp and such that are really just hacks to the 1.x versions of React-scripts.

I had thought since it has just been added as a dependency we could get some assistance on how and where to add configurations. When I include Workbox in my registerServiceWorker.js and attempt to set some strategies on assets it crashes the entire app once built.

Unable to import module 'workbox-routing' from 'WORKBOX_CDN_ROOT_URL/workbox-routing.prod.js'.

I understand serviceworkers are now opt-in. I understand that in the latest version of create react app the service worker register file is now just called serviceworker.js.

I compared the old registerServiceWorker.js to the new serviceworker.js and they are the same. I also am able to build with the default service worker file and I do see Workbox in the application tab in Chrome dev tools. I know its working out of the box. I just want to be able to edit it. Guidance would be greatly appreciated.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:6
  • Comments:22

github_iconTop GitHub Comments

26reactions
karannaguptacommented, Dec 12, 2018

Here’s how I’ve done it with CRA and without ejecting. It uses the workbox build workflow. (cra 2.x)

TL;DR - This involves not using the SW generated by create-react-app but generating your own SW with injectManifest mode using the Workbox build workflow. Build commands will be added to react-build script in package.json

NOTE: Keep an eye on #5369 I think it will allow configuring Workbox using the Webpack workflow using a custom configuration file.

Step1 : Make sure you register for a SW in the main index.js file. i.e. change serviceWorker.unregister(); to serviceWorker.register();

Step2: Inside src/serviceWorker.js in window.addEventListener('load', () => { change the swURL to point to a new file (this is what will be created in the build step) so, change this - const swUrl = ``${process.env.PUBLIC_URL}/service-worker.js``; to const swUrl = ``${process.env.PUBLIC_URL}/sw.js``;

Step3: Create two files under src/ - sw-build.js and sw.js

Step4: In sw-build.js add the code as provided by Google’s injectManifest example here -

const workboxBuild = require('workbox-build');
// NOTE: This should be run *AFTER* all your assets are built
const buildSW = () => {
  // This will return a Promise
  return workboxBuild.injectManifest({
    swSrc: 'src/sw.js', // this is your sw template file
    swDest: 'build/sw.js', // this will be created in the build step
    globDirectory: 'build',
    globPatterns: [
      '**\/*.{js,css,html,png}',
    ]
  }).then(({count, size, warnings}) => {
    // Optionally, log any warnings and details.
    warnings.forEach(console.warn);
    console.log(`${count} files will be precached, totaling ${size} bytes.`);
  });
}
buildSW();

Step 5: Inside your custom service worker template file i.e. src/sw.js add the injection point and your cache rules. e.g - in the file src/sw.js -

if ('function' === typeof importScripts) {
  importScripts(
    'https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js'
  );
  /* global workbox */
  if (workbox) {
    console.log('Workbox is loaded');

    /* injection point for manifest files.  */
    workbox.precaching.precacheAndRoute([]);

/* custom cache rules*/
workbox.routing.registerNavigationRoute('/index.html', {
      blacklist: [/^\/_/, /\/[^\/]+\.[^\/]+$/],
    });

workbox.routing.registerRoute(
      /\.(?:png|gif|jpg|jpeg)$/,
      workbox.strategies.cacheFirst({
        cacheName: 'images',
        plugins: [
          new workbox.expiration.Plugin({
            maxEntries: 60,
            maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
          }),
        ],
      })
    );

} else {
    console.log('Workbox could not be loaded. No Offline support');
  }
}

step 6: npm install workbox-build --save-dev I think workbox-build is already included in node_modules, but good idea to make an entry in package.json

step 7: in package.json add the workbox build step so, in package.json, under scripts add a new entry - "build-sw": "node ./src/sw-build.js" and then change: "build": "react-scripts build to "build": "react-scripts build && npm run build-sw

When your run npm run build you will see the the file sw.js inside your build folder. The CRA generated service-worker.js will continue to be there. You can run a build command to clear it, but it won’t be used because we change the swURL in step2.

Again, all of this may not be relevant if #5369 provides a way to use the webpack flow by providing a custom configuration file.

2reactions
Rainson12commented, Nov 14, 2018

@Nick-t-go from what i have seen in the other blog posts they all dont work with the current v2 create react app scripts as they all try to get rid of sw-precache and use workbox instead. Now with v2 you dont have to get rid of sw-precache anymore and because of that, all guides i have seen are obsolete and do not work anymore

Read more comments on GitHub >

github_iconTop Results From Across the Web

The ways of Workbox - Chrome Developers
Get familiar with some of the ways you can use Workbox. ... our service worker requirements are simple enough to be covered by...
Read more >
Workbox - web.dev
Workbox aims to make using service workers as easy as possible while allowing the flexibility to accommodate complex application requirements where needed.
Read more >
Ultimate Guide to PWAs with Workbox
This guide will take you through your own practical build where you'll learn Workbox to complete a real PWA! I'm excited to take...
Read more >
Getting started with progressive web applications through ...
In this tutorial, we're going to explore how to make web applications work offline through the use of service workers generated from Workbox,...
Read more >
Build A PWA With Webpack And Workbox - Smashing Magazine
Using a tool to generate your service worker is the recommended approach as it lets you manage your cache efficiently. We will be...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found