如何使用Create-React-App和自定义服务人员构建PWA
Note: This is not a primer on create-react-app or what a service worker is. This post assumes prior knowledge of both.
注意:这不是create-react-app或服务工作者的入门。 这篇文章假定两者都有先验知识。
So, I recently had the opportunity to work on a React project which involved publishing the resulting web application as a Progressive Web Application (PWA).
因此,我最近有机会从事一个React项目,该项目涉及将生成的Web应用程序发布为Progressive Web Application(PWA)。
I realised what a struggle it is to get a PWA with custom routes configured inside of a Create React App (CRA) build. Hopefully this helps out someone stuck in a similar position.
我意识到,要在Create React App(CRA)构建中配置自定义路由的PWA很难。 希望这可以帮助陷入类似困境的人。
Create-React-App中的PWA (PWAs in Create-React-App)
How exactly do we get a PWA running inside our CRA shell?
我们如何才能在CRA外壳中运行PWA?
Now, the CRA shell bundles a service worker by default. You should have noticed that in a basic CRA shell, inside of the index.js
file, there is a call to registerServiceWorker
:
现在,默认情况下,CRA Shell将服务工作者捆绑在一起。 您应该已经注意到,在基本的CRA shell中,在index.js
文件中,有一个对registerServiceWorker
的调用:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
You can create a new CRA app and look inside the registerServiceWorker
file.
您可以创建一个新的CRA应用程序并查看registerServiceWorker
文件。
It looks quite complex, but it is really just checking to see if the environment variables are set for a production build and if a serviceWorker
is supported in the current browser.
它看起来很复杂,但实际上只是检查是否为生产版本设置了环境变量,以及当前浏览器是否支持serviceWorker
。
If you run a build with the command yarn build
, you can open up the build folder and check inside to see that a service-worker.js
file has been generated. This is the default service worker file CRA generates for you.
如果使用yarn build
命令运行构建,则可以打开build文件夹并在内部检查是否已生成service-worker.js
文件。 这是CRA为您生成的默认服务工作者文件。
The formatting of the file is inline ES5 JavaScript, which makes it a little hard to read. But you can dump it into any prettifier, and you should see a more legible file.
该文件的格式是内联ES5 JavaScript,这使得它有点难以阅读。 但是您可以将其转储到任何修饰词中,并且应该看到更清晰的文件。
Looking into the above file should show you that it is simply creating a static cache with the following cache name: sw-precache-v3-sw-precache-webpack-plugin-+(selg.registration ? self.registration.scope)
. It then caches all of your static files like index.html
and your js
and css
files inside of that cache.
查看上面的文件应该显示给您,它只是使用以下缓存名称创建静态缓存: sw-precache-v3-sw-precache-webpack-plugin-+(selg.registration ? self.registration.scope)
。 然后,它将所有静态文件(如index.html
以及js
和css
文件缓存在该缓存中。
You should also see a fetch
event listener in there that catches a fetch event and checks to see if the app is requesting one of the previously cached static assets.
您还应该在其中看到fetch
事件侦听器,该侦听器将捕获获取事件并检查应用程序是否正在请求先前缓存的静态资产之一。
Now comes the million dollar question: what if you want to configure a dynamic cache for a specific route? In essence, a cache that will update itself with data sent from the server when the user visits a specified route. Note that this means the data will not be available at build time, and therefore cannot be cached by the default service worker generated.
现在是百万美元的问题:如果要为特定路由配置动态缓存,该怎么办? 本质上是一种缓存,当用户访问指定的路由时,它将使用服务器发送的数据来更新自身。 请注意,这意味着数据在构建时将不可用,因此无法由生成的默认服务工作者缓存。
CRA中默认PWA的限制 (Limitations of default PWAs in CRA)
Unfortunately, it’s not very easy to accomplish the above when using CRA. Unless you’re willing to eject
, of course.
不幸的是,使用CRA时要完成上述任务并非易事。 当然,除非您愿意eject
。
Take a look at these GitHub issues to see why the team at CRA won’t support customising the default service worker.
查看这些GitHub问题,以了解CRA团队为何不支持自定义默认服务工作者。
Custom ServiceWorker config · Issue #2237 · facebook/create-react-app1.0.0 added Progressive Web App support, is it possible to support custom config in near future? I really don't want to…github.comImport scripts in Service Worker by piotr-cz · Pull Request #2714 · facebook/create-react-appThis PR adds an ability to use importScripts option of SWPrecacheWebpackPlugin. How-to: create a file called…github.com
自定义ServiceWorker配置·问题#2237·添加了facebook / create-react-app 1.0.0渐进式Web App支持,是否有可能在不久的将来支持自定义配置? 我真的不想…… github.com 通过piotr-cz在Service Worker中导入脚本·拉取请求#2714·facebook / create-react-app 此PR添加了使用SWPrecacheWebpackPlugin的importScripts选项的功能。 操作方法:创建一个名为… github.com 的文件
So, given that we can’t seem to customise the default service-worker, how do we work our way around it?
因此,鉴于我们似乎无法自定义默认的服务工作者,我们将如何解决呢?
了解CRA如何生成服务工作者 (Understanding How CRA Generates A Service Worker)
The first step to finding a work around for the build system is to actually understand how the build system works.
寻找解决方案的第一步是真正了解构建系统的工作原理。
So, let’s start with the library the build system uses to generate a service worker file.
因此,让我们从构建系统用来生成服务工作者文件的库开始。
sw-precache
is a library that allows you to generate a service worker file based on a template. The template file is written using underscore’s templating engine.
sw-precache
是一个库,使您可以基于模板生成服务工作者文件。 模板文件是使用下划线的模板引擎编写的。
Here is the link to the template file in the sw-precache
source code.
这是sw-precache
源代码中模板文件的链接。
Again, the template file looks complex, but it is quite straightforward once you manage to get your head around the templating language.
同样,模板文件看起来很复杂,但是一旦您设法绕过模板语言,它就非常简单。
So, what happens when you run a build process in a CRA shell, in relation to generating a service worker, is:
因此,相对于生成服务工作者,在CRA Shell中运行构建过程时会发生以下情况:
The
sw-precache
library is executed internallysw-precache
库在内部执行An options object is provided to
sw-precache
to allow generation of the service worker file from the template将选项对象提供给
sw-precache
以允许从模板生成服务工作者文件The service worker file is generated in the
build
folder with the nameservice-worker.js
在名称为
service-worker.js
的build
文件夹中生成service worker文件。
覆盖默认服务工作者 (Overriding The Default Service Worker)
Now, how do we override the above process to allow our own custom service worker file to be generated?
现在,我们如何覆盖上面的过程,以允许生成我们自己的定制服务工作者文件?
The answer is based on Jeff Posnick’s (a maintainer of sw-precache
) stackoverflow answer.
答案基于Jeff Posnick( sw-precache
的维护者) stackoverflow答案 。
First, we need to run thesw-precache
CLI after the normal build process.
首先,我们需要在正常的构建过程之后运行sw-precache
CLI。
Install the sw-precache
library by running the following command: npm install --save-dev sw-precache
通过运行以下命令来安装sw-precache
库: npm install --save-dev sw-precache
Now, the sw-precache
library runs on a config file, which is provided via an option on the CLI. This is the command: sw-precache --config=sw-precache-config.js
, where sw-precache-config.js
is the name of the config file.
现在, sw-precache
库在配置文件上运行,该配置文件通过CLI上的选项提供。 这是命令: sw-precache --config=sw-precache-config.js
,其中sw-precache-config.js
是配置文件的名称。
Here is a sample config file.
这是一个示例配置文件。
module.exports = {staticFileGlobs: ['build/static/css/**.css','build/static/js/**.js'],swFilePath: './build/service-worker.js',templateFilePath: './service-worker.tmpl',stripPrefix: 'build/',handleFetch: false,runtimeCaching: [{urlPattern: /this\\.is\\.a\\.regex/,handler: 'networkFirst'}]
}
Note: It is important that you specify the swFilePath as ./build/service-worker.js
This is so that the service worker generated as a result of your custom build process overwrites the one created by CRA (they both share the same name, in this instance). Otherwise, you will end up with two service worker files in your build directory!
注意:您指定的swFilePath,因为它是重要的./build/service-worker.js
这是这样,作为您的自定义生成过程的结果所产生的服务人员将覆盖CRA创建的(他们都有着相同的名字,在这种情况下)。 否则,您将在构建目录中获得两个Service Worker文件!
There is extensive documentation on the object properties and what valid values can be assigned to them on the GitHub page for sw-precache
.
有大量关于对象属性的文档,以及可以在sw-precache
的GitHub页面上为它们分配哪些有效值。
Of special interest is the runtimeCaching option, because this is a very extensible solution to allow you to define custom rules for your service worker to respond to dynamic content.
特别有趣的是runtimeCaching选项,因为这是一个非常可扩展的解决方案,允许您为服务工作者定义自定义规则以响应动态内容。
The templateFilePath is an option for when you want the CLI to pick up your custom service worker template file. But you’re almost always going to be using the template file provided by the library itself.
templateFilePath是您希望CLI拾取自定义服务工作程序模板文件时的选项。 但是您几乎总是会使用库本身提供的模板文件。
Finally, we need to provide the script to signal to the CRA build system that we want our custom service worker to be generated. Go ahead and install the sw-precache
library.
最后,我们需要提供脚本以向CRA构建系统发出信号,告知我们要生成我们的定制服务工作者。 继续并安装sw-precache
库。
Next, update the package.json build script, with the following:
接下来,使用以下命令更新package.json构建脚本:
build: react-scripts build && sw-precache --config=sw-precache-config.js
build: react-scripts build && sw-precache --config=sw-precache-config.js
Once you run the build process with npm run build
, you can open up the build folder and see your generated service worker.
使用npm run build
运行构建过程后,您可以打开build文件夹并查看生成的服务工作程序。
Run the build process with and without the custom service worker and notice the differences between the two.
在有和没有定制服务工作者的情况下运行构建过程,并注意两者之间的差异。
结论 (Conclusion)
While this may seem like a very verbose approach to something as simple as customising a service worker, this approach has the benefit of keeping you firmly within the create-react-app shell.
尽管这对于像定制服务人员这样的简单操作来说似乎是非常冗长的方法,但是这种方法的好处是可以使您牢牢地处于create-react-app shell中。
There are other approaches to generating a custom service worker (using a combination of react-app-rewire and workbox). I’ll try and get that approach up in a post as well.
还有其他生成自定义服务工作程序的方法(结合使用react-app-rewire和workbox )。 我也会尝试在帖子中提出这种方法。
翻译自: https://www.freecodecamp.org/news/how-to-build-a-pwa-with-create-react-app-and-custom-service-workers-376bd1fdc6d3/
相关文章:

inline-block空隙怎么解决
方法一:移除空格 元素间留白间距出现的原因就是标签段之间的空格,因此,去掉HTML中的空格,自然间距就木有了。考虑到代码可读性,显然连成一行的写法是不可取的,我们可以: <div class"spa…

php 网络请求 get请求和post请求
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码记录 <?php header(content-type:application:json;charsetutf8); header(Access-Control-Allow-Origin:*); //header(Access-Control-Allow-Methods:POST); header(Access-Control-Allow-He…

docker查看现有容器_如何使用Docker将现有应用程序推送到容器中
docker查看现有容器by Daniel Newton丹尼尔牛顿 如何使用Docker将现有应用程序推送到容器中 (How to shove an existing application into containers with Docker) I have finally got round to learning how to use Docker past the level of knowing what it is and does w…

巧妙使用Firebug插件,快速监控网站打开缓慢的原因
巧妙使用Firebug插件,快速监控网站打开缓慢的原因 原文 巧妙使用Firebug插件,快速监控网站打开缓慢的原因 很多用户会问,我的网站首页才50KB,打开网页用了近60秒才打开?如何解释? 用户抱怨服务器运行缓…

第二阶段第三次站立会议
昨天做了什么:写了部分购物车的功能 今天要干什么:修改后台代码的错误 遇到的困难:没有困难转载于:https://www.cnblogs.com/jingxiaopu/p/7109774.html

微信小程序生成小程序二维码 php 直接可以用
微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 小程序需要先上线才能生成二维码 HTTP请求的效果图: 小程序展示的效果图: 小程序展示二维码源码: 请求二维码图片base64路径,点击预览图片 onLoad: func…

vue和react相同点_我在React和Vue中创建了相同的应用程序。 这是区别。
vue和react相同点by Sunil Sandhu由Sunil Sandhu 我在React和Vue中创建了相同的应用程序。 这是区别。 (I created the same app in React and Vue. Here are the differences.) Having used Vue at my current workplace, I had a fairly solid understanding of how it all …

Filter(过滤器)
一、Filter过滤器(重要) Javaweb中的过滤器可以拦截所有访问web资源的请求或响应操作。 1、Filter快速入门 1.1、步骤: 1. 创建一个类实现Filter接口 2. 重写接口中方法 doFilter方法是真正过滤的。 3. 在web.xml文件中配置 …

css3实现3D立体翻转效果
1、在IE下无法显示翻转效果,火狐和谷歌可以 1 /*样式css*/2 3 .nav-menu li {4 display: inline;5 }6 .nav-menu li a {7 color: #fff;8 display: block;9 text-decoration: none;10 overflow: visible;11 line-height: 40px;12 font-…

Ant Design 入门-参照官方文档使用组件
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 先来一个按钮组件使用的对比,官方文档的(不能直接用)和实际能用的。 官网demo: import { Table, Divider, Tag } from antd;const columns = [{title: Name,dataIndex: name,key: name,render: text =…

如何用JavaScript的回调函数做出承诺
by Adham El Banhawy由Adham El Banhawy 如何用JavaScript的回调函数做出承诺 (How to make a Promise out of a Callback function in JavaScript) Back-end developers run into challenges all the time while building applications or testing code. As a developer who …

VMware里的linux系统里的命令行里会有bee的声音,要如何关掉
VMware里的linux系统里的命令行里会有bee的声音,要如何关掉 取消bell报警声的方法:登陆linux系统vi /etc/inputrc找到set bell-style none 将前面的#去掉,之后重启系统即可解决声音问题若不见效可以通过下面的方式解决下bell-styl…

React-Todos
最近学完React的最基本概念,闲下来的时候就自己写了一个Todo-List的小应用。这里做个简略的说明,给想好好学React的新手看。 React-Todo 学习前提 这里我用了webpackb做了babel和JSX预处理和模块打包。所以对React和一些ES2015(ES6࿰…

Ant Design 入门-引用自己命名的组件
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 自己创建的组件:代码 import { Table, Divider, Tag } from antd; import React, { Component } from react; export default class My_Table extends Component {render() {const columns = [{title: …

迷宫出路代码_如何在软件开发的迷宫中找到自己的出路
迷宫出路代码by Tim Kleier蒂姆克莱尔(Tim Kleier) 如何在软件开发的迷宫中找到自己的出路 (How to find your way through the corn maze of software development) The corn maze is one of my favorite challenges to tackle. It’s an unnerving experience, especially w…

打包 React 项目并在服务器运行。
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1.找到项目根目录的package.json文件:如图: 2.打开cmd执行:npm run build 3.生成DIST文件夹。 4.把DIST文件放到服务器phpStudty根目录,访问index.html。…

一些有用的Python问题
1. 修改IDLE工作路径,在命令交互模式下输入如下指令: >>> import os >>> os.getcwd() #查看当前的工作路径 >>> os.chdir(E:\\Python\\Demo) #修改当前的工作路径 2.Python中 ImportError: cannot import name NUMPY_MKL 的…

Python核心编程笔记---- print
在仅用变量名时,输出的字符串是用单引号括起来的。这个是为了让非字符串对象也可能以字符的形式显示在屏幕上。 而print 函数打印出来的是变量的值。 print 调用的是str()方法。而仅用变量名时调用的是repr()方法。 证明:------------------------------…

latex 插图解释_大O符号-只需插图和视频即可解释
latex 插图解释Big O notation is used to communicate how fast an algorithm is. This can be important when evaluating other people’s algorithms, and when evaluating your own! In this article, I’ll explain what Big O notation is and give you a list of the m…

[YTU]_2002(C语言实验——单词统计)
Description 从键盘输入一行字符,统计其中单词的个数,各单词以空格分隔,且空格数可以是多个。Input 输入只有一行句子。仅有空格和英文字母构成。 Output 单词的个数。 Sample Input stable marriage problem Consists of Matching memb…

资本中国人物-金融
一、二、三、店、五、土地、七、八、玖、拾起、白、千、一万、一亿、元(圆)、角、支、零、整个。这是上图中我们经常要填写。问:什么是它用数词?想必很多人都不是很清楚! 请看下面的两个相关的表数词: 1、数字化和大、小写数字对照…

Ant Design Pro 网络请求流程
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 在 Ant Design Pro 中,一个完整的前端 UI 交互到服务端处理流程是这样的: UI 组件交互操作; 调用 model 的 effect; 调用统一管理的 service 请求函数&a…

在Google Cloud Platform上持续部署Node.js
by Gautam Arora由Gautam Arora 在Google Cloud Platform上持续部署Node.js (Continuous Deployment for Node.js on the Google Cloud Platform) Google Cloud Platform (GCP) provides a host of options for Node developers to easily deploy our apps. Want a managed ho…

hdu-1108 最小公倍数
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid1108 题目类型: 数论 题意概括: 求两个数的最小公倍数 解题思路: 模拟 题目: 最小公倍数 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/O…

sql-schema与catalog
schema: 指的是说当偶create database caiceclb时,caiceclb就是一个schema catalog: 指的是所有的database目录,就像上图显示的那样,将MySQL原来的(mysql,infomation_schema)及后来新建的的data…

这是如何更好地利用JavaScript数组的方法
by pacdiv由pacdiv 这是如何更好地利用JavaScript数组的方法 (Here’s how you can make better use of JavaScript arrays) Quick read, I promise. Over the last few months, I noticed that the exact same four mistakes kept coming back through the pull requests I c…

07、C语言——函数
函数 1、函数定义 函数返回值类型 函数名(形式参数列表) { 函数体; } 注意: 定义有参函数时,形参的定义可以采用传统方式或现代方式两种 1)传统方式: int …

This is probably not a problem with npm. There is likely additional logging output above
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 E:\weii_objct\invoice-manage-web-view>npm start > ant-design-pro@2.1.0 start E:\weii_objct\invoice-manage-web-view > cross-env APP_TYPE=site umi dev cross-env 不是内部或外部命令…

parcel react_如何使用Parcel捆绑React.js应用程序
parcel reactby Michael Ozoemena迈克尔奥索埃梅纳(Michael Ozoemena) 如何使用Parcel捆绑React.js应用程序 (How to use Parcel to bundle your React.js application) 什么是包裹? (What’s Parcel?) Parcel is a web application bundler which offers a blazi…

SparkSQL 与 Spark Core的关系
不多说,直接上干货! SparkSQL 与 Spark Core的关系 Spark SQL构建在Spark Core之上,专门用来处理结构化数据(不仅仅是SQL)。 Spark SQL在Spark Core的基础上针对结构化数据处理进行很多优化和改进, 简单来讲: Spark SQ…