DEV Community

Doug Reeder
Doug Reeder

Posted on

Adding Service Worker to old app started with create-react-app

Years ago, I started my app using create-react-app. IIRC, there was an option to create it with a service worker, which I declined. Some years later, I ejected my app. Now, I'd like to add a Service Worker.

create-react-app

According to Workbox in CRA this is just a matter of changing

serviceWorker.unregister();
Enter fullscreen mode Exit fullscreen mode

to

serviceWorker.register();
Enter fullscreen mode Exit fullscreen mode

but there is no such unregister line, and no import * as serviceWorker from './serviceWorker'; to import it, and no serviceworker source file.

In webpack.config.js, there is the line

// Get the path to the uncompiled service worker (if it exists).
const swSrc = paths.swSrc;
Enter fullscreen mode Exit fullscreen mode

which uses

  swSrc: resolveModule(resolveApp, 'src/service-worker'),
Enter fullscreen mode Exit fullscreen mode


in paths.js

When I add a NOP service worker in 'src/service-worker', running npm run build evokes the following error:

Creating an optimized production build...
Failed to compile.

Can't find self.__WB_MANIFEST in your SW source.
Enter fullscreen mode Exit fullscreen mode

which is a Workbox error.

workbox-webpack-plugin

Workbox: using a bundler tells me to include

import {GenerateSW} from 'workbox-webpack-plugin';
Enter fullscreen mode Exit fullscreen mode

in my webpack.config.js. Adding this gets the error

SyntaxError: Cannot use import statement outside a module
Enter fullscreen mode Exit fullscreen mode

because the webpack.config.js created by create-react-app using Node.js style imports.

workbox-cli

I then installed workbox-cli and used npx workbox wizard to create workbox-config.js with default parameters (/build is the directory I deploy from.)

npx workbox generateSW workbox-config.js indeed creates /build/sw.js and friends, but they are deleted by node scripts/build.js. If I build, run workbox generateSW and deploy, /sw.js is indeed on the server, but the file is never fetched by my app.

When I change workbox-config.js to output to src/service-worker.js, building my app again gets the error

Creating an optimized production build...
Failed to compile.

Can't find self.__WB_MANIFEST in your SW source.
Enter fullscreen mode Exit fullscreen mode

So, what is the route to adding a Service Worker to my app created with CRA?

Top comments (1)

Collapse
 
doug_reeder profile image
Doug Reeder

FWIW, my solution was to switch to using vite - it treats ECMAscript modules as the default and non-modules as the exception.