反应脚本构建服务工作者不缓存自定义文件 [英] react scripts build service worker not caching custom files

查看:47
本文介绍了反应脚本构建服务工作者不缓存自定义文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到由 react-scrips 构建生成的 Service Worker 不会缓存某些文件.这些文件包括(在我的项目中)公共文件夹中的自定义 css 文件和一些从其他服务器访问的文件(例如谷歌字体和引导 css 文件).

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?

非常感谢

所以 react 构建脚本会在/build 中生成 service-worker.js 文件.然而,生成的 Service Worker 无法按预期工作.服务工作者缓存诸如/index.html 之类的文件和所有/static/* 文件(它们也是由 react-script 构建生成的),但是它不会缓存例如/bootstrap-override.css(这是一个由me) 和 bootstrap css,它是从地址 https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css.如何让 Service Worker 也缓存这些文件?

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?

推荐答案

React 使用 SWPrecache 来缓存 webpack 构建的所有文件.因此,如果您希望缓存 css,则需要将其包含在您的 React 应用程序中(而不是包含在 index.html 中).在 app.jsx 中添加:

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';

但是您不能从 cdn 导入,因此您需要从 npm 获取引导程序并导入它.

But you can't import from a cdn, so you'll need to get bootstrap from npm and import it.

另一种解决方案是通过执行 npm run eject 来弹出配置脚本这允许您通过配置 SWPrecachePlugin 来配置 Service Worker 缓存哪些文件.在 webpack.config 中:

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' : ''
    }
})

这篇关于反应脚本构建服务工作者不缓存自定义文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆