问题
It has come to my attention that the service worker generated by the react-scrips build does not cache certain files. Those files include (in my project) a custom css file in the public folder and some files accessed from other servers (such as google fonts and bootstrap css files).
How do I make sure that those files are cached too?
Thank you alot
EDIT: So the react build script generates the service-worker.js file in /build. The generated service worker does not work as wished however. The service worker caches files such as /index.html and all /static/* files (which are also generated by the react-script build) however it does not cache for example /bootstrap-override.css (which is a file created by me) and the bootstrap css which is retrieved with a simple tag in index.html from the address https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css. How can I get the service worker to cache those files too?
回答1:
React use SWPrecache to cache all files that webpack builds. So if you want your css to be cached, you need to include it in your react app (and not in the index.html). add inside app.jsx :
import 'bootstrap-override.css';
But you can't import from a cdn, so you'll need to get bootstrap from npm and import it.
Another solution is to eject the config scripts by doing npm run eject
This allows you to configure which files are cached by the service worker by configuring the SWPrecachePlugin. in webpack.config :
new SWPrecacheWebpackPlugin({
filename: "../service-worker.js",
...
staticFileGlobs: [
"/bootstrap-override.css" //Additional static files
],
dynamicUrlToDependencies: {
//Add external assets here
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' : ''
}
})
来源:https://stackoverflow.com/questions/51874665/react-scripts-build-service-worker-not-caching-custom-files