I need a way to exclude URLs from a service-worker scope in create-react-app without having to eject. The service-worker is being generated and I cannot see any way how I could change this functionality without having to eject.
Asked
Active
Viewed 1,634 times
2
-
Possible duplicate of [Add more service-worker functionality with create-react-app](https://stackoverflow.com/questions/47636757/add-more-service-worker-functionality-with-create-react-app) – Jeff Posnick Apr 11 '18 at 19:23
-
Does this answer your question? [Setting service worker to exclude certain urls only](https://stackoverflow.com/questions/45663796/setting-service-worker-to-exclude-certain-urls-only) – apaatsio Sep 25 '20 at 18:00
1 Answers
4
Here is my solution.
Create a script outside of the src/
directory called rebuild-service-worker.js
, with the following contents:
"use strict";
const FS = require("fs");
let text = FS.readFileSync("./build/service-worker.js").toString();
const start = text.indexOf("blacklist: [");
const end = text.indexOf("\n", start) - 2;
text = text.substring(0, end) + ",/^\\/admin/" + text.substring(end);
FS.writeFileSync("./build/service-worker.js", text);
As you can see, it adds a new item to the blacklist: []
array that is part of the Workbox configuration.
Then, in your package.json
build
script, simply call it after react-scripts build
like this:
"scripts": {
"build": "react-scripts build && node ./rebuild-service-worker",
...

Wayne Bloss
- 5,370
- 7
- 50
- 81