Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

javascript - How do I exclude url's from service worker scope in create react app, without having to eject?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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("
", 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",
    ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...