如何使用create-react-app自定义服务人员

高明辉
2023-12-01

This is a follow up to my previous post about building a PWA with create-react-app (CRA). In the linked post, I discussed how we could go about building a custom Service Worker (SW) while staying within the create-react-app shell.

这是我之前关于使用create-react-app(CRA)构建PWA的文章的后续文章 。 在链接的文章中,我讨论了如何在停留在create-react-app shell内的同时构建自定义Service Worker(SW)。

If you followed along with the post (and hopefully got it working), you’d have noticed one critical flaw. It is still extremely hard to develop a SW in a dev environment. Essentially, you’d have to modify your SW code, run a build process, test it out, iron out any bugs, refresh and repeat. Speaking from experience, it is an exhausting process.

如果您关注该帖子(并希望它能正常工作),您将注意到一个关键缺陷。 在开发环境中开发SW仍然非常困难。 本质上,您必须修改SW代码,运行构建过程,对其进行测试,消除所有错误,刷新并重复。 从经验上来讲,这是一个疲惫的过程。

Let’s go ahead and figure out how to solve that problem.

让我们继续前进,找出解决问题的方法。

在开发模式下工作 (Working In Dev Mode)

Okay, so how do we get a SW running in dev mode, so we can quickly write some bad code, and figure out what works and what doesn’t?

好的,那么我们如何使SW在开发模式下运行,以便我们可以快速编写一些错误的代码,并确定哪些有效,哪些无效?

First, let’s figure out why it doesn’t work in dev mode. Create a fresh CRA project, and open up the registerServiceWorker.js under the src directory.

首先,让我们弄清楚为什么它在开发模式下不起作用。 创建一个新的CRA项目,并打开src目录下的registerServiceWorker.js

In the above gist, I only have the relevant piece of code. You will notice a conditional check process.env.NODE_ENV === 'production'. This is checking to see if you are running a production build. If you aren’t running a production build, the SW will be replaced by a no-op file.

在以上要点中,我只有相关的代码段。 您会注意到有条件检查process.env.NODE_ENV === 'production' 。 这是在检查您是否正在运行生产版本。 如果您不运行生产版本,则SW将被无操作文件替换。

The reasoning behind this decision is provided in this GitHub issue.

该决定背后的原因在GitHub问题中提供

First, try and run yarn start on your app and check for a SW file in the toolbar window. If you click on the service-worker.js link in the toolbar, you will be shown the following file:

首先,尝试在您的应用程序上运行yarn start ,并在工具栏窗口中检查SW文件。 如果单击工具栏中的service-worker.js链接,将显示以下文件:

Fortunately, there is a simple fix for this. It’s an easy two-step process.

幸运的是,有一个简单的解决方案。 这是一个简单的两步过程。

First, inside of the registerServiceWorker.js file, look for the window.addEventListener('load') function call. The first line is a declaration for swUrl which says:

首先,在registerServiceWorker.js文件中,查找window.addEventListener('load')函数调用。 第一行是swUrl的声明,声明:

const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

Rename the service-worker part of it with anything else. I’m going to name mine service-worker-custom.js.

用其他任何名称重命名service-worker部分。 我将命名为mine service-worker-custom.js

Second, create a file inside of your public directory with the exact same name as the custom name you just came up with. So, I would create a file called service-worker-custom.js inside of the public directory.

其次,在您的公共目录内创建一个文件,其名称与您刚想到的自定义名称完全相同 。 因此,我将在公共目录内创建一个名为service-worker-custom.js的文件。

Now, inside of the service-worker-custom.js , place a simple log statement. Something like: console.log('My custom service worker').

现在,在service-worker-custom.js放置一个简单的日志语句。 类似于: console.log('My custom service worker')

Now, run your app again with yarn start and you should see the log statement pop up in your browser console. You might need to unregister a previous service worker if you ever ran yarn start prior to this.

现在,使用yarn start再次运行您的应用程序,您应该在浏览器控制台中看到日志语句弹出。 如果您在此之前进行过纱线启动工作,则可能需要注销以前的服务人员。

So, there you have it. A custom service worker that you can run safely inside of dev mode.

所以你有它。 您可以在开发人员模式下安全运行的自定义服务工作者。

Note: It is unwise to test a service worker in a dev env outside of private browsing mode in your browser. Also, always make sure Update On Reload is checked inside your dev tools window when testing in dev mode.

注意:在浏览器的私有浏览模式以外的开发环境中测试服务工作者是不明智的。 此外,在开发人员模式下进行测试时,请务必确保在开发人员工具窗口中选中了“重载时更新”。

结合开发和生产 (Combining Dev and Prod)

Now, we’ve figured out how to test a SW in dev mode. However, we also need to find a way to inject our custom code into the SW generated by CRA in a production build.

现在,我们已经找到了如何在开发模式下测试软件。 但是,我们还需要找到一种方法,将自定义代码注入到由CRA在生产版本中生成的SW中。

If you keep everything as is with the configurations we’ve made so far and run a build process and check the build in your browser, you will notice that the SW file generated is the custom one we created. This is a problem, because we want to be able to combine the goodness of what CRA has to offer us with our own code.

如果您按照我们到目前为止所做的配置保留所有内容,并运行构建过程并在浏览器中检查构建,您会注意到生成的SW文件是我们创建的自定义文件。 这是一个问题,因为我们希望能够将CRA提供给我们的代码的优点与我们自己的代码结合起来。

We can do this with thesw-precache library. I introduced this library in my previous post. Here is the GitHub link to the sw-precache library.

我们可以使用sw-precache库来做到这一点。 我在上一篇文章中介绍了这个库。 这是指向 sw-precache库的GitHub链接

Install the library with yarn add sw-precache . Once you’ve done that, create a sw-precache-config.js file in your root directory. Here is my file:

使用yarn add sw-precache安装库。 完成此操作后,在根目录中创建一个sw-precache-config.js文件。 这是我的文件:

I’ve introduced most of this file in the previous post. The only new bit is the importScripts option. This is fairly self-explanatory, it simply imports the file specified by the path, and we are trying to import our custom SW file.

在上一篇文章中,我已经介绍了大部分文件。 唯一的新功能是importScripts选项。 这是不言自明的,它只是导入由路径指定的文件,我们正在尝试导入自定义的SW文件。

You will notice that the path of the file lacks the ./public prefix, despite the file being present in our public directory. I’ll explain this in a bit.

您会注意到,尽管文件位于我们的public目录中,但文件路径缺少./public前缀。 我会稍作解释。

Now, update your package.json file with a modification to the build command. Make your build command the following:

现在,使用对build命令的修改来更新package.json文件。 使您的build命令如下:

react-scripts build && sw-precache --config=sw-precache-config.js

react-scripts build && sw-precache --config=sw-precache-config.js

Now, let’s go back to the file path we provided to the importScripts option. If you notice, the sw-precache is essentially running as a post build process. Now, if you just run a build process, and open up the build directory that is created, you will notice your custom service worker file in the build folder. When we provide a path to the importScripts option, we are providing it relative to the build directory!

现在,让我们回到为importScripts选项提供的文件路径。 如果您注意到, sw-precache实际上是作为后构建过程运行的。 现在,如果您只是运行构建过程,并打开已创建的构建目录,您将在构建文件夹中注意到您的自定义服务工作者文件。 当我们提供importScripts选项的路径时,我们将提供相对于build目录的路径!

Once, you’ve done all of that, go ahead and run the build version of your app, and you will notice that the log statement pops up once again in your browser console.

一旦完成所有这些操作,继续并运行应用程序的构建版本,您会发现log语句再次在浏览器控制台中弹出。

Well, there you have it! You can now inject some custom SW code into the default SW generated by CRA!

好吧,那里有! 您现在可以向CRA生成的默认SW中注入一些自定义SW代码!

翻译自: https://www.freecodecamp.org/news/how-to-customize-service-workers-with-create-react-app-4424dda6210c/

 类似资料: