customize your service worker in create react app without `npm run eject`
š· Customize your service worker in create react app without npm run eject
Create-react-app provides built-in service-worker.js but _when you want to extend it_ \
(e.g. to cache REST API response) you need to do npm run eject and maintain more configs.
Sometimes we just want to enjoy customization but keep those big configs unchanged. \
This cli tool helps you achieve this with ease.
https://sw-precache-cra-demo-cra-contributors.netlify.com/
A page caching GitHub API response with [one simple config][sw-config]. Done in [4 steps][examples-sw-precache-cra]
1. $ npm i -S sw-precache-cra
2. Edit the build script in package.json
There are 2 examples:
š” If you want your service worker _cache API response with url /messages_:
concat the build script
``diff`
"scripts": {
"start": "react-scripts start",
- "build": "react-scripts build",
+ "build": "react-scripts build && sw-precache-cra --config sw-config.js",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
with one additional js module having any [sw-precache configs][sw-precache-configs]:
`js`
// sw-config.js
module.exports = {
runtimeCaching: [
{
urlPattern: '/messages',
handler: 'networkFirst',
},
],
};
š You've got custom build/service-worker.js after npm run build
---
š” If you want to have _Non minified_ build/service-workder.js you can do this:
`diff`
"scripts": {
"start": "react-scripts start",
- "build": "react-scripts build",
+ "build": "react-scripts build && sw-precache-cra --no-minify",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
š You've got Un-minified build/service-worker.js after npm run build
`bash
$ sw-precache-cra --list-config
For more APIs please do
sw-precache-cra --help`- Add more service-worker functionality with create-react-app
- [sw-precache README][sw-precache-configs]
- facebook/create-react-app issue #3132
- bbhlondon/cra-append-sw
[MIT License][mit-license]
[mit-license]: https://liuderchi.mit-license.org/ "mit-license"
[sw-precache-configs]: https://github.com/GoogleChromeLabs/sw-precache#options-parameter "sw-precache-config"
[sw-config]: https://github.com/liuderchi/sw-precache-cra/blob/examples/examples/cra-contributors/sw-config.js
[examples-sw-precache-cra]: https://github.com/liuderchi/sw-precache-cra/commits/examples