万能工具箱万能工具箱_角度工作箱简单指南

万能工具箱万能工具箱

Simple yet powerful Service Worker for Angular

简单但功能强大的Angular服务工作者

Service Workers provide an excellent way to provide better offline capabilities for Web Apps.

服务工作者提供了一种出色的方式来为Web Apps提供更好的脱机功能。

While Angular provides its own Service Worker capability, it comes as a take-it or leave-it option.

尽管Angular提供了自己的Service Worker功能 ,但它是“接受”还是“离开”选项。

If you want a more powerful and configurable solution, integrating Workbox and Angular is a good option.

如果您想要一个更强大且可配置的解决方案,那么将Workbox和Angular集成是一个不错的选择。

背景 (Background)

There are some good sources available both for WHY you might want to integrate Workbox and Angular and HOW to do it. I have included three sources in the Resources at the end of the article. All of these sources have contributed to the documented solution.

对于为什么您可能想将Workbox和Angular以及HOW集成在一起,都有一些很好的资源。 我在本文结尾处的参考资料中包括了三个资源。 所有这些来源都为文档解决方案做出了贡献。

The TLDR: is that if you want more control over the service worker than is provided by the angular service worker, then Workbox provides a good way of doing this. Workbox is a service worker javascript library that also comes out of the Google stable. Workbox 5 is webpack/rollup and TS ready.

TLDR:是,如果您想要对服务人员的控制多于角度服务人员所提供的控制,那么Workbox提供了一种很好的方法。 Workbox是服务工作者的javascript库,它也来自Google稳定版。 Workbox 5已准备好Webpack /汇总和TS。

However, these sources all seem to emphasis the complexities of integrating the two (and since a powerful solution is the aim, there can be a lot of complexities). In this article, I want to create a simple recipe for the integration or Angular and Workbox.

但是,所有这些来源似乎都强调了将两者集成的复杂性(并且由于目标是强大的解决方案,因此可能会有很多复杂性)。 在本文中,我想为集成或Angular and Workbox创建一个简单的配方。

基础 (The Basics)

This article assumes Workbox version 5 or later. We are going to use the bundler approach to Workbox, for the performance benefits it brings and because it is now the recommended approach. We are going to create and manage the Workbox configuration in Typescript and we are going to use webpack as the bundler, both of these for compatibility with angular (although since there are actually no compile-time dependencies this should not be necessary). Finally, we are going to use the injectManifest Workbox configuration since the whole aim of doing this is to get the full capabilities of Workbox.

本文假定使用Workbox版本5或更高版本。 我们将对Workbox使用捆绑程序方法,以为其带来的性能优势,因为现在推荐使用此方法。 我们将在Typescript中创建和管理Workbox配置,并且将webpack用作捆绑程序,两者都是为了与angular兼容(尽管由于实际上没有编译时依赖性,所以这不是必需的)。 最后,我们将使用injectManifest Workbox配置,因为这样做的全部目的是获得Workbox的全部功能。

Given all of the above, the build process for the service worker is as follows:

鉴于以上所有内容,服务工作者的构建过程如下:

  1. You create a swtemplate.ts file that specifies the caching strategies for the app,

    您创建一个swtemplate.ts文件,该文件指定应用程序的缓存策略,
  2. This is compiled into es2015 by the webpack ts-loader and the libraries are then bundled in by webpack,

    这是由webpack ts-loader编译到es2015中,然后这些库由webpack捆绑在一起,
  3. Finally, the workbox cli creates the “precache manifest” (i.e. a list of URLs with version numbers for the files that should be preached by the app). This is injected into the file and saved as sw.js. This is the service worker.

    最后,工作箱cli创建“预缓存清单”(即,URL列表,其中包含应由应用程序宣告的文件的版本号)。 这被注入文件并保存为sw.js。 这是服务人员。

This means that the service worker is unique for each angular build since the manifest will be different. The runtime configuration (below) then needs to reload the new version, which will refresh the cache with the new angular build.

这意味着,由于清单不同,因此服务工作者对于每个角度构建都是唯一的。 然后,运行时配置(如下所示)需要重新加载新版本,这将使用新的角度构建刷新缓存。

We need to create the configurations for each of these stages.

我们需要为每个阶段创建配置。

You may notice that there are many similarities between this process and angular’s build process :) Unfortunately, you cannot combine the two into one build, all of the configurations will clash.

您可能会注意到,此过程与angular的构建过程之间有许多相似之处:)不幸的是,您无法将两者组合为一个构建,所有配置都会冲突。

安装 (Installation)

Over and above the basic angular project we are going to have to install Workbox. This actually comes as a set of modules but a good starting point is as follows:

除了基本的角度项目,我们将必须安装Workbox。 这实际上是一组模块,但是一个很好的起点如下:

npm install workbox-core workbox-precaching workbox-routing workbox-strategies workbox-cacheable-response workbox-expiration workbox-window
npm install workbox-cli -D
npm install webpack webpack-cli -D
npm install ts-loader -D

Finally, create a folder in your src folder to hold the workbox assets — called workbox.

最后,在src文件夹中创建一个文件夹来保存工作箱资产-称为workbox

TS配置 (TS Config)

First, we have to set up the TS environment. You will need a file called tsconfig.json in the workbox folder and add the following content:

首先,我们必须建立TS环境。 您将在工作箱文件夹中需要一个名为tsconfig.json的文件,并添加以下内容:

{
"compilerOptions": {
"typeRoots" : ["./typings"],
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"lib": [
"esnext", "webworker"]
},
"files": ["./swtemplate.ts"],
}

We then create the swtemplate.ts file in the workbox folder. This recipe is not going to be a lesson in creating this file — there are more than enough resources out there about that. for information, I have added a typical version with comments as a gist in the Resources section. There is, however, a minimum set of contents that you will need and it is pretty much this :

然后,我们在workbox文件夹中创建swtemplate.ts文件。 创建此文件不会使您汲取教训—那里有足够的资源来解决这个问题。 有关信息,我在参考资料部分中添加了带有注释的典型版本。 但是,您将需要最少的内容集,几乎是这样的:

import {skipWaiting, clientsClaim} from 'workbox-core';
import {precacheAndRoute, cleanupOutdatedCaches} from 'workbox-precaching';declare const self: ServiceWorkerGlobalScope;skipWaiting();
clientsClaim();
cleanupOutdatedCaches();/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/precacheAndRoute(self.__WB_MANIFEST);

This will just prefetch and cache as per the config for workbox.cli down the page. You can reasonably start with this config and incrementally add caching rules to meet your needs.

这将按照页面下workbox.cli的配置预取和缓存。 您可以合理地从此配置开始,并逐步添加缓存规则以满足您的需求。

WebPack配置 (WebPack Config)

The next step is to provide the webpack config.

下一步是提供webpack配置。

Create a file called webpack.config.js in the workbox folder. Make the contents:

在工作箱文件夹中创建一个名为webpack.config.js的文件。 使内容:

var path = require('path');module.exports = {
mode: 'production',
entry: './swtemplate.ts',
output: {
path: path.resolve(__dirname, '.'),
filename: 'swtemplate.js'
},
module: {
rules: [{
test: /\.ts$/,
loader: 'ts-loader'
}]
},
resolve: { extensions: [".js", ".ts"] }
};

This config will compile and build one file (swtemplate.ts) into one file (swtemplate.js) bundling the dependencies.

该配置将编译一个文件(swtemplate.ts)并将其构建为一个捆绑依赖项的文件(swtemplate.js)。

At this point, you can run a manual test to make sure it is all working — by running (in the workbox folder)

在这一点上,您可以运行一个手动测试以确保一切正常—通过运行(在workbox文件夹中)

npx webpack swtemplate.ts --config webpack.config.js`

The basic swtempate.ts provided above should build into a file about 11KB long. The production mode will have ensured that the file is minified.

上面提供的基本swtempate.ts应该内置到大约11KB长的文件中。 生产模式将确保文件已缩小。

Workbox-cli配置 (Workbox-cli Config)

The final step in the build process is to create and inject the manifest.

构建过程的最后一步是创建并注入清单。

To do this we need to create a file called workbox-config.js in the workbox folder. This should have the contents :

为此,我们需要在workbox文件夹中创建一个名为workbox-config.js的文件。 这应该具有以下内容:

module.exports = {
globDirectory: "<-- replace with path angular build dir-->",//This is a good start for ngx but edit to match your app
globPatterns: [
"*.{png,svg,jpg,txt,gif,css,js,ico,eot,ttf,woff,json}",
"assets/*.{png,svg,jpg,ico,gif}
],
globFollow: true, // follow symlinks
globStrict: true, // fail on error
globIgnores: [// Ignore Angular's ES5 bundles
`**/*-es5.js*`,
"sw.js"
],// Don't need to cachebust angular files
dontCacheBustURLsMatching: new RegExp(".+.[a-f0-9]{20}..+"),// Set large files to catch the angular vendor.js files. It is up to the developer to ensure the cache is not overwhelmed
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,
swDest: "<-- replace with path for sw.js -->/sw.js",
swSrc: "./swtemplate.js"
};

There are two configuration items you need to decide in this file — the location of the sw.js file and the GlobDirectory path. In general, you want the sw.js file to be at the root of your site (so that you get the correct service worker scope). This would normally be next to the index.html and for a fairly standard angular build — this would be the build location for angular. You need to set the globDirectory such that the path from that location to the angular files (e.g. main.js) is the same as the relative URL used to access them. Again, in a standard build this would be set to the build location thus making the relative URL for main.js to be “/main.js”. NOTE — both of these paths are relative to the workbox folder — i.e. would normally look something like ‘../../’.

您需要在此文件中确定两个配置项-sw.js文件的位置和GlobDirectory路径。 通常,您希望sw.js文件位于站点的根目录(以便获得正确的service worker范围 )。 通常是在index.html旁边,并且对于一个相当标准的角度构建-这将是角度的构建位置。 您需要设置globDirectory,以使从该位置到角度文件(例如main.js)的路径与用于访问它们的相对URL相同。 同样,在标准构建中,将其设置为构建位置,从而使main.js的相对URL为“ /main.js”。 注意—这两个路径都是相对于workbox文件夹的,即通常看起来类似于“ ../../”。

Once this is configured, you can manually test it using the command (in the workbox folder)

配置完成后,您可以使用命令(在工作箱文件夹中)手动对其进行测试

workbox injectManifest

This should work and should report the correct number of files to be cached and should generate sw.js in the correct place.

这应该可以工作,并且应该报告要缓存的正确文件数,并且应该在正确的位置生成sw.js。

构建脚本 (Build Script)

We now have two commands that need to be run. The webpack command actually only needs to be run when swtemplate.ts changes, but it does not harm if run more often, and the workbox command needs to be run every time angular does a build.

现在,我们有两个需要运行的命令。 实际上,仅在swtemplate.ts更改时才需要运行webpack命令,但是如果更频繁地运行webpack命令并不会造成损害,并且每次angular进行构建时都需要运行workbox命令。

There are a range of ways to set up the build, but my favourite is the simplest. Set up a shell script to be tun by npm build that includes something like the following

有多种方法来建立构建,但我最喜欢的是最简单的方法。 设置要由npm build调整的shell脚本,其中包括以下内容

ng build <build options>
cd src/workbox
npx webpack swtemplate.ts --config webpack.config.ts
workbox injectManifest

运行时配置 (Run-Time Configuration)

The next step is that the app needs to be changed to use (i.e. register ) the service worker.

下一步是需要更改应用程序以使用(即注册)服务工作者。

The one I propose as the easiest and most performant is to change main.ts to include the following new lines

我建议的最简单,最有效的方法是更改​​main.ts以包括以下新行

import {Workbox} from 'workbox-window'function loadServiceWorker() {
if ('serviceWorker' in navigator) {
const wb = new Workbox('/sw.js');
wb.register();
}
}

and to change the bootstrap command to

并将bootstrap命令更改为

platformBrowserDynamic().bootstrapModule(AppModule)
.then( _=> loadServiceWorker())
.catch(err => console.error(err));

This will load and register the service worker, if the browser supports service workers.

如果浏览器支持服务人员,则将加载并注册服务人员。

The other part of the run-time configuration is updating the service worker when it changes. There is a huge amount of online information about how to do this in various scenarios. The code above, along with the very simplistic use of skip_waiting() and claim_client() in the swtemplate.ts, provides the most simplistic mechanism whereby after a new version of sw.js is pushed (i.e. after every angular build is published) — this is downloaded on the next page refresh and once it has downloaded immediately becomes active. Note that there are a number of circumstances where this simplistic approach can break your app. Having said that, I have had great success with this approach with simple Web Apps. You just have to be careful about updates to fundamental logic.

运行时配置的另一部分是更改服务程序时对其进行更新。 有关在各种情况下如何执行此操作的大量在线信息。 上面的代码以及swtemplate.ts中对skip_waiting()和Claim_client()的非常简单的使用,提供了最简单的机制,即在推送新版本的sw.js之后(即,在发布每个角度构建之后)—它会在下一页刷新时下载,下载后立即变为活动状态。 请注意,在许多情况下,这种简单的方法可能会破坏您的应用程序。 话虽如此,我在使用简单Web Apps的这种方法上已经取得了巨大的成功。 您只需要注意基本逻辑的更新即可。

开发生产 (Development and Production)

You have probably noticed that the simple recipe I have proposed does not make any differences for production and development environments, and actually just produces the build required for the production environment.

您可能已经注意到,我提出的简单配方对于生产和开发环境没有任何区别,实际上只是生成了生产环境所需的构建。

Well. This is the simple recipe! Follow the resources below if you wish to create dev and prod builds.

好。 这是简单的食谱! 如果您想创建dev和prod版本,请遵循以下资源。

I will say that I personally would not build the service worker into the angular ng serve development environment. It complicates debugging too much. I do anyway do frequent production builds into a web server on my dev machine for continuous integration testing and I would develop and test the service worker in that environment.

我会说,我个人不会将服务人员构建到有角度的服务开发环境中。 它使调试变得非常复杂。 无论如何,我都会在我的dev机器上频繁地将产品构建到Web服务器中,以进行持续集成测试,并且我将在该环境中开发和测试服务人员。

客制化 (Customisation)

Almost everything about this recipe is configurable — which is the benefit that we were trying for. Following the documentation and resources below to bend this recipe to your needs.

关于此配方的几乎所有内容都是可配置的,这就是我们试图获得的好处。 按照下面的文档和资源,使此食谱符合您的需求。

资源资源 (Resources)

I would suggest the following to start:

我建议以下内容开始:

and

and

The Workbox documentation is here

Workbox文档在这里

Finally, this is a typical example of a complete swtemplate.ts file.

最后,这是完整的swtemplate.ts文件的典型示例。

import {skipWaiting, clientsClaim} from 'workbox-core';
import {precacheAndRoute, cleanupOutdatedCaches} from 'workbox-precaching';
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate, CacheFirst, NetworkFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';


declare const self: ServiceWorkerGlobalScope;


skipWaiting();
clientsClaim();
cleanupOutdatedCaches();


/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 * See https://goo.gl/S9QRab
 */




precacheAndRoute(self.__WB_MANIFEST);


// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
registerRoute(
  /^https:\/\/fonts\.googleapis\.com/,
  new StaleWhileRevalidate({
    cacheName: 'google-fonts-stylesheets',
  })
);


// Cache the underlying font files with a cache-first strategy for 1 year.
registerRoute(
  /^https:\/\/fonts\.gstatic\.com/,
  new CacheFirst({
    cacheName: 'google-fonts-webfonts',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 60 * 60 * 24 * 365,
        maxEntries: 31,
      }),
    ],
  })
);


// cache the data request so that, if the network is off we get the last good response
registerRoute(
  '/database',
  new NetworkFirst({
    cacheName: 'static-resources',
  })
);


// cache the root - needed to get PWA accreditation
registerRoute(
  '/',
  new StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);


// cache any external libraries
registerRoute(
  /http.*\.(?:js|css|mjs)$/,
  new CacheFirst({
    cacheName: 'libraries',
    plugins: [
      new ExpirationPlugin({
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  }),
);


//cache any external images
registerRoute(
  /\.(?:png|gif|jpg|jpeg|svg)$/,
  new CacheFirst({
    cacheName: 'images',
    plugins: [
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  }),
);

翻译自: https://medium.com/runic-software/simple-guide-to-workbox-in-angular-197c25396e68

万能工具箱万能工具箱

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值