通过create-react-app添加更多服务工作者功能 [英] Add more service-worker functionality with create-react-app
问题描述
因此create-react-app包括服务工作者功能 ,这很可爱-我所有的静态资产都已缓存,可以脱机使用。很酷,但是现在我想进一步介绍一下,并使用indexedDB缓存一些动态内容。
So create-react-app includes service worker functionality by default, which is lovely - all my static assets get cached for offline use out of the box. Cool, but now I want to take things a bit further and use indexedDB to cache some dynamic content.
问题是,没有service-worker.js文件可以修改。它是在构建过程中生成的。
Problem is, there's no service-worker.js file to modify. It gets generated during the build process.
有没有一种方法可以添加其他逻辑,而无需弹出create-react-app或重做所有不错的静态缓存内容?
Is there a way to add additional logic without ejecting create-react-app or redoing all the nice static caching stuff?
推荐答案
如您所见, create-react-app
的配置为锁定,并且服务工作者逻辑完全在配置中定义。
As you've observed, create-react-app
's config is locked down, and the service worker logic is entirely defined in the config.
如果您不想 eject
但是您需要自定义,另一种选择是修改 create-react-app
生成过程以显式调用 sw-precache
CLI 之后,正常构建完成,覆盖 create-react-app <
service-worker.js
/ code>默认生成。因为这涉及到修改本地 package.json
,所以不需要先执行 eject
。
If you'd rather not eject
but you want some customization, another option is to modify the create-react-app
build process to explicitly call the sw-precache
CLI after the normal build has completed, overwriting the service-worker.js
that create-react-app
generates by default. Because this involves modifying your local package.json
, it doesn't require eject
ing first.
有关此方法的一些信息这里,通常的想法是修改您的 npm
脚本,使其类似于:
There's some info on this approach here, and the general idea is modifying your npm
scripts to look something like:
"build": "react-scripts build && sw-precache --config=sw-precache-config.js"
使用 sw-precache-config.js
已根据您的需要进行配置,但包括
swFilePath: './build/service-worker.js'
确保内置 service-worker.js
被覆盖。
这篇关于通过create-react-app添加更多服务工作者功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!