Skip to content

Instantly share code, notes, and snippets.

@kivervinicius
Created November 25, 2019 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kivervinicius/4f4c1911ee0355eee7fc703a20f3d7c0 to your computer and use it in GitHub Desktop.
Save kivervinicius/4f4c1911ee0355eee7fc703a20f3d7c0 to your computer and use it in GitHub Desktop.
CRA Workbox change
const fs = require("fs");
function template (preCacheFile, blackList) {
return `/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
* See https://goo.gl/nhQhGp
*
* The code below was initially generated by WorkBox but because
* CRA doesn't allow blacklist customization "yet", run the node
* command "bin/changeServiceWorker.js" after each build.
*/
importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
importScripts(
"/${preCacheFile}"
);
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
workbox.core.clientsClaim();
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
// teste
workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("/index.html"), {
blacklist: [/^\\/_/, /\\/[^\\/?]+\\.[^\\/]+$/${blackList ? "," + blackList : ""}],
});
`;
}
const blackList = `/api/`;
const buildDir = "./build";
const dir = fs.readdirSync(buildDir);
const swFile = dir.filter(function (elm) {
return elm.match(/precache-manifest/gi);
})[0];
if (!swFile) {
throw new Error("Not found file precache-manifest");
}
fs.writeFileSync(buildDir + "/service-worker.js", template(swFile, blackList));
@kivervinicius
Copy link
Author

add in your package.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment