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();
to
serviceWorker.register();
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;
which uses
swSrc: resolveModule(resolveApp, 'src/service-worker'),
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.
which is a Workbox error.
workbox-webpack-plugin
Workbox: using a bundler tells me to include
import {GenerateSW} from 'workbox-webpack-plugin';
in my webpack.config.js. Adding this gets the error
SyntaxError: Cannot use import statement outside a module
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.
So, what is the route to adding a Service Worker to my app created with CRA?
Top comments (1)
FWIW, my solution was to switch to using vite - it treats ECMAscript modules as the default and non-modules as the exception.