Search code examples
javascriptreactjsservice-workerprogressive-web-appsworkbox

Register a service-worker in index.html file that's located in SRC folder - ReactJS


Run service-worker from other folder

I'am trying to use service-worker to precache entire of PWA and i need to locate SW inside of SRC folder.

How can I run my SW from public/index.html?

I use create-react-app and i use google workbox to generate service-worker.

I try to import SW into App.js file, but I catch an error:

'importScripts' is not defined no-undef

importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/5.0.0/workbox-sw.js"
);

const precacheManifest = []; 

workbox.routing.registerRoute(
  new RegExp("https://app.tessa.technology/api/"),
  new workbox.strategies.CacheFirst()
);

workbox.routing.registerRoute(
  new RegExp(
  "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
),
new workbox.strategies.CacheFirst()
);


 workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);
  • public
    • manifest.js
    • index.html
  • SRC
    • JS
    • CSS
    • SW.js

Solution

  • You have two ways.

    1) Put your service-worker.js file in public directory.

    2) Or, use the workbox-webpack-plugin. With this way the service-worker.js will be generate and imported automatically. This way is more recommended.