I have created a react app using create-react-app. Then I decided I need to edit/update the service worker code as per my need.
I am trying to build the app now using sw-precache (as its supposed to help building the custom service worker and automatically refer to the hashed static files).
This is the config I am using in 'sw-precache-config.js' -
module.exports = {
staticFileGlobs: [
'build/static/css/**.css',
'build/static/js/**.js',
'index.html',
'/'
],
swFilePath: './build/serviceWorker.js',
templateFilePath: './service-worker.tmpl',
stripPrefix: 'build/',
handleFetch: false,
runtimeCaching: [{
urlPattern: /this\\.is\\.a\\.regex/,
handler: 'networkFirst'
}]
}
This is the build command in my package.json -
"build": "react-scripts build && sw-precache --config=sw-precache-config.js",
However, I am facing two issues after the build -
Even though I have mentioned in the config file that the service worker name should be 'serviceWorker.js', the build process is generating two service worker files -
serviceWorker.js and service-worker.js
In the generated serviceWorker.js (build by the build script), 'index.html' file is not being mentioned in the precache (so the service worker is not caching index.html as intended)-
var precacheConfig =
[["static/css/main.d35a7300.chunk.css","5cf96316c6919194ba6eb48522a076f0"],["static/js/1.6105a37c.chunk.js","ae3537cefdcf8ee5758c3af13aab4568"],["static/js/main.4857c4da.chunk.js","9d6cc8fb962129f3e8bc459c85d39297"],["static/js/runtime~main.229c360f.js","3b44b5daad3fcbefa8b355dfbc3d9630"]];
Please let me know if I can clarify anything else.
Replace index.html
in staticFileGlobs
with build/index.html
You are getting two service worker files because the name you are specifying: serviceWorker.js
is different from the default name CRA goes with: service-worker.js
Change your swFilePath
to service-worker.js
and that should fix it.