简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM