angular 模块构建
by Tomiwa
通过Tomiwa
In this article, you will learn the theory of how service workers work. I provide a short tutorial to apply that theory to make a website that runs without the internet. Finally, I’ll discuss what this means for you and the future of the internet.
在本文中,您将学习服务人员如何工作的理论。 我提供了一个简短的教程,以应用该理论建立一个无需互联网即可运行的网站。 最后,我将讨论这对您和互联网的未来意味着什么。
I get excited when talking about service workers. I am going to go on a quick rant on the problem this solves and why this is awesome. Then I dive into the theory of how service workers work and why it is awesome. If you want to jump straight to the theory or the tutorial, go to the sections starting with titles Theory and Application for the code.
当谈到服务人员时,我很兴奋。 我将就解决的问题以及为什么如此出色进行快速调查。 然后,我将深入探讨服务人员的工作原理以及为何如此出色。 如果您想直接跳到理论或教程,请转至以“ 理论和应用”标题开头的部分。
This blog post is also available as:
该博客文章也可通过以下方式获得:
Youtube Video
YouTube视频
Slide deck
滑板
Podcast
播客
I realized something recently that made me truly realize how powerful service workers can be. When I have internet, it feels like there are infinitely many things competing for my attention.
最近我意识到,使我真正意识到服务人员的能力将是多么强大。 当我拥有互联网时,感觉就像有无数事物在吸引我的注意力。
But when I am on a plane for example, and there is no internet connection, the competition for my attention is much less fierce. The three things I can usually do is look through my photos, watch a downloaded movie or read an ebook.
但是,例如,当我在飞机上且没有互联网连接时,引起我注意的竞争就不会那么激烈。 我通常可以做的三件事是浏览照片,观看下载的电影或阅读电子书。
With service-workers, if you are able to deliver an offline web experience for your users, you are able to get their attention in one of those few moments when the competition for it is least fierce.
使用服务人员,如果您能够为用户提供脱机的Web体验,则您可以在竞争最激烈的那一瞬间获得他们的关注。
Let’s start with a simple diagram. What do the two circles in this Venn diagram represent?
让我们从一个简单的图开始。 该维恩图中的两个圆圈代表什么?
Let me give you a hint. Amazon, Alibaba, and Facebook are some of the world’s biggest websites, servicing millions of users every day. Here are some stats to put things in context for you:
让我给你一个提示。 亚马逊,阿里巴巴和Facebook是世界上最大的网站,每天为数百万用户提供服务。 以下是一些统计数据,可为您提供相关信息:
Alibaba $25 billion in sales in one day (singles day)
阿里巴巴一天内(一天)的销售额达到250亿美元
40% of cloud computing clients use Amazon Web Services Including Apple, Netflix, and CIA
40%的云计算客户使用包括苹果 ,Netflix和CIA在内的Amazon Web Services
2.2 Billion people use Facebook every month, 700 million on Instagram
每月有22亿人使用Facebook,Instagram上有7 亿人
This is all well and good but there’s just one small problem. Without wifi, their entire websites are completely unusable. Even if you just want to do simple tasks like look at product reviews for items that are already in your shopping cart, you can’t do anything.
这一切都很好,但是只有一个小问题。 没有wifi,他们的整个网站将完全无法使用。 即使您只想执行简单的任务,例如查看购物车中已有商品的产品评论,也无法做任何事情。
Now compare that to sites like Google Drive or Atila.ca. Atila.ca doesn’t have a million users but even when you have no internet connection, you can still use the site. Google Drive is another website that does this well. You can actually use Google Drive even without internet. Like how you would use a desktop app like Microsoft Word. Learn something new everyday right?
现在将其与Google Drive或Atila.ca之类的网站进行比较。 Atila.ca没有一百万用户,但是即使您没有互联网连接,您仍然可以使用该网站。 Google云端硬盘是另一个做得很好的网站。 即使没有互联网,您实际上也可以使用Google云端硬盘。 就像您如何使用Microsoft Word这样的桌面应用程序一样。 每天学习新东西吧?
In the past, it almost seemed like a truism that websites would not work without the internet. Once you realize the potential of service workers, you completely change your perspective on how you think about websites. You begin to imagine the significant user experience improvements we can have on our favorite sites.
过去,如果没有互联网,网站将无法正常运行,这似乎是不言而喻的。 一旦意识到服务人员的潜力,就可以完全改变对网站的看法。 您开始想象我们可以在我们喜欢的网站上获得重大的用户体验改善。
Imagine if you are on the subway commuting to work with no internet. You do not even have any cell phone service. But you could still review the product reviews of the items in your Amazon shopping cart. Or you’re on a long plane ride. While your phone is in airplane mode you can read the most popular articles from The New York Times. Or your favorite articles in a list that you chose to save for later.
想象一下,如果您在地铁上通勤而没有互联网。 您甚至没有任何手机服务。 但是您仍然可以查看亚马逊购物车中商品的商品评论。 或者您正在乘坐长途飞机。 当手机处于飞行模式时,您可以阅读《纽约时报》上最受欢迎的文章。 或您喜欢的文章,然后选择保存以供以后保存。
You can see that the potential is great and it easy to start daydreaming. Let’s get back to reality and dig into the theory of how this is all possible.
您会看到潜力很大,并且很容易开始做白日梦。 让我们回到现实,并深入探讨一切皆有可能的理论。
A service worker is a proxy or messenger between your browser and the internet. When your web app asks for resources (images, html files, json API etc.) the service worker gets it for you without needing to ask the internet. In literal terms, it is a Javascript file that gets shipped along with the rest of your app. This file has code that tells your app how to intercept network requests and get it from your network cache.
服务人员是您的浏览器和Internet之间的代理或使者。 当您的Web应用程序请求资源(图像,html文件,json API等)时,服务人员无需为互联网服务即可为您获取资源。 从字面上看,它是一个Javascript文件,与您的应用程序的其余部分一起提供。 该文件的代码告诉您的应用如何拦截网络请求并从网络缓存中获取请求。
Typically, when a website is first loaded, the web browser makes a set of requests to the network for the assets that your website needs to run. Typically including:
通常,在首次加载网站时,Web浏览器会向网络发出一组请求,以请求您网站需要运行的资产。 通常包括:
When your internet is not working, there is no way for the browser to contact the network to retrieve the files necessary for displaying the website. So it fails and you get the infamous “jumping Dinosaur” on Google Chrome.
当您的Internet无法正常工作时,浏览器无法与网络联系以检索显示网站所需的文件。 因此失败了,您在Google Chrome上看到了臭名昭著的“跳跃恐龙”。
With service workers. The first time you visit a site, in addition to the usual set of index.html, styles.css, main.js etc. files that get requested, the browser also requests a service worker javascript file from your website. This file then gets downloaded and saved to your browser cache. The serviceworker file then downloads, versions and caches all the files in your application to serve it for later.
与服务人员。 首次访问网站时,浏览器除了会请求通常的index.html,styles.css,main.js等文件集外,还会从您的网站上请求服务人员javascript文件。 然后下载此文件并将其保存到浏览器缓存中。 然后,serviceworker文件下载,版本化和缓存应用程序中的所有文件,以供以后使用。
This has two very important benefits. As is mentioned in the title, this means that even when your internet connection is down, the website will still work. It never actually has to ask the internet for anything. The service worker has all the files you will need.
这有两个非常重要的好处。 如标题中所述,这意味着即使您的Internet连接断开,该网站仍然可以正常工作。 它实际上不需要向互联网提出任何要求。 服务人员拥有您将需要的所有文件。
Conversely, this also means that even if you do have internet, the application will also run faster. On future website loads, instead of making a full round trip to the network to get the application files. It simply retrieves the files from the browser cache and serves it to the user.
相反,这也意味着即使您有互联网,该应用程序也会运行得更快。 在将来的网站加载中,而不是进行整个网络往返以获取应用程序文件。 它只是从浏览器缓存中检索文件并将其提供给用户。
Before you start make sure you have the following installed
在开始之前,请确保已安装以下组件
Node.js® and npm
Node.js®和npm
Globally install Angular CLI:
全局安装Angular CLI :
npm install -g @angular/cli
npm install -g @angular/cli
Go to https://github.com/atilatech/atila-web-app
转到https://github.com/atilatech/atila-web-app
Clone the demo.atila.ca web app from Github: atila-web-app
从Github克隆demo.atila.ca Web应用程序: atila-web-app
Check out the pwa-tutorial branch: git checkout pwa-tutorial
git checkout pwa-tutorial
出pwa-tutorial分支: git checkout pwa-tutorial
Check out the tutorial start commit: git checkout pwa-tutorial-0.0
git checkout pwa-tutorial-0.0
出教程开始提交: git checkout pwa-tutorial-0.0
Install npm modules: npm install
安装npm模块: npm install
Start the app!: ng serve -o
启动应用程序!: ng serve -o
If you get a No NgModule
error, go to any .ts file and put a space. This is a really strange bug but you can read this Github issue for more information.
如果出现No NgModule
错误,请转到任何.ts文件并放置一个空格。 这是一个非常奇怪的错误,但是您可以阅读此Github问题以获取更多信息。
In order to install the Service Worker and get access to the various Service Worker objects in our app, we need to do the following.
为了安装Service Worker并访问我们应用程序中的各种Service Worker对象,我们需要执行以下操作。
You can check out the official angular documentation on servicer worker configuration for more details
您可以查看有关servicer worker配置的正式角度文档,以了解更多详细信息。
{"name": "Atila","short_name": "Atila","start_url": "index.html","display": "standalone","icons": [{"src": "assets/img/favicon-bg.png","sizes": "512x512","type": "image/png"}],"background_color": "#194f87","theme_color": "#194f87"}
This is what turns your app from a web app to a progressive web app. It allows your web app to be similar to a native mobile. It allows users to install your app to their home screen.
这就是将您的应用程序从Web应用程序变为渐进式Web应用程序的原因。 它使您的Web应用程序类似于本地移动设备。 它允许用户将您的应用安装到其主屏幕。
Now we need to actually tell our app that a service worker exists. So we register the service worker module in our app module.
现在,我们需要实际告诉我们的应用程序存在服务工作者。 因此,我们在应用程序模块中注册了服务工作者模块。
// src/app.module.ts
import {ServiceWorkerModule} from '@angular/service-worker';
…
Imports: [
…,
ServiceWorkerModule.register('/ngsw-worker.js', {enabled: environment.production}),]
Then we register the service worker file if our browser has service worker support and we are are in production mode.
然后,如果我们的浏览器支持Service Worker并且我们处于生产模式,那么我们将注册Service Worker文件。
// src/main.ts
if ('serviceWorker' in navigator && environment.production) {
console.log("Service Worker in main.ts");
window.addEventListener('load', () =>; {
console.log("on page Load Service Worker in main.ts");
navigator.serviceWorker.register('/ngsw-worker.js', {
scope: '/',
})
.then(registration =>; {
console.log("Service Worker registration completed main.ts", registration);
});
});
Next, we will build the project: ng build --prod
接下来,我们将构建项目: ng build --prod
Let’s take a look at the dist/ folder to see what building an app with service worker looks like.
让我们看一下dist /文件夹,看看使用Service Worker构建应用程序的样子。
Recall that in the previous step we created a file called ngsw-config.json. This file specifies what types of files we wanted our service worker to cache and how we wanted to cache it. When the project gets built, the rules in the ngsw-config.json gets expanded to include exactly what files we will be caching. The ngsw.json file also includes a hash table to index and retrieve the cached files. The hash table also allows us to version our files. We can keep track of what versions of our file is running and if we should get a new version.
回想一下,在上一步中,我们创建了一个名为ngsw-config.json的文件。 该文件指定我们希望我们的服务工作者缓存什么类型的文件以及我们希望如何缓存它。 构建项目后,ngsw-config.json中的规则将扩展为确切包含我们将要缓存的文件。 ngsw.json文件还包含一个哈希表,用于索引和检索缓存的文件。 哈希表还允许我们对文件进行版本控制。 我们可以跟踪文件的哪些版本正在运行以及是否应该获取新版本。
This file is literally the service worker. We registered it earlier in our main.ts file. It is a plain javascript file. It contains the code and logic for how your service worker registers and caches data to a database. If you’re up for a challenge, try looking through the code and see if you can understand what is happening.
该文件实际上是服务工作者。 我们之前在main.ts文件中注册了它。 这是一个普通的javascript文件。 它包含有关服务工作者如何将数据注册和缓存到数据库的代码和逻辑。 如果您面临挑战,请尝试查看代码,看看是否可以理解正在发生的事情。
Install npm http server
安装npm http服务器
Npm install [email protected] --save-dev
Npm install [email protected] --save-dev
ng build --prod
(optional)
ng build --prod
(可选)
http-server -p 8080 -c-1 dist
http-server -p 8080 -c-1 dist
Open http://localhost:8080/
打开http:// localhost:8080 /
Note that there is no wi-fi in the top right. Check the devtools console: The external network resources fail with 504 but our files are successful (200).
请注意,右上角没有wi-fi。 检查devtools控制台:外部网络资源失败504,但我们的文件成功(200)。
Open the application tab in Devtools and you will see the local cache section. This is the “database” where the service workers are saving your files. That there are 2 tables. One which contains the actual resources our app needs. Another hash table with hash keys that point to each file name, as we saw in our ngsw.json file. That’s it! You now have a simple but functional offline first web app. Continue to part 2 for adding more cool features.
在Devtools中打开应用程序选项卡,您将看到本地缓存部分。 这是服务人员保存文件的“数据库”。 那有2张桌子。 一种包含我们应用程序所需的实际资源。 正如我们在ngsw.json文件中看到的那样,另一个带有哈希键的哈希表指向每个文件名。 而已! 您现在有了一个简单但功能强大的脱机优先Web应用程序。 继续第2部分,添加更多酷功能。
When you try to navigate click on a link, you will notice a server error. Your service worker doesn’t have those APIs in your database, but we can add it. Pop Quiz! If we want to tell our service worker to cache a new type of file where should we put the code to do so:
当您尝试导航时,单击链接,您会注意到服务器错误。 您的服务工作者在数据库中没有这些API,但我们可以添加它。 突击测验! 如果我们想告诉我们的服务工作者将一种新型文件缓存在哪里,我们应该将代码放在哪里:
You can see the network requests failing in your dev tools network tab.
您可以在开发工具的“网络”标签中看到网络请求失败。
Now we will configure our ngsw-config.json to cache external API URLs as well. Two caching options:
现在,我们将配置ngsw-config.json来缓存外部API URL。 两种缓存选项:
You might need to use a separate URL that allows your app to access it via CORS. We will use a special JSON service to simulate (“mock”) our blog API. We don’t have permission to use official Atila API’s
您可能需要使用单独的URL,该URL允许您的应用通过CORS访问它。 我们将使用特殊的JSON服务来模拟(“模拟”)博客API。 我们无权使用官方的Atila API
Go to src/app/_service/scholarship.service.ts#L47
转到src/app/_service/scholarship.service.ts#L47
Change: this.http.post(${this.scholarshipsPreviewUrl}?page=${page}/, form_data)
to: this.http.get(https://api.myjson.com/bins/dx1dc
)
将: this.http.post(${this.scholarshipsPreviewUrl}?page=${page}/, form_data)
更改为:this.http.get( https://api.myjson.com/bins/dx1dc
)
Change: this.http.get(${this.blogUrl}blog/${username}/${slug}/
) to: this.http.get(https://api.myjson.com/bins/v5ow0
)
更改:this.http.get( ${this.blogUrl}blog/${username}/${slug}/
)到:this.http.get( https://api.myjson.com/bins/v5ow0
)
When a new version is available from the network, the service worker still serves the old version in the cache to save time
当网络上有新版本可用时,服务工作者仍在缓存中提供旧版本以节省时间
Then we create swUpdate to listen for updates from the SW and update if a new version is available.Github Diff
然后,我们创建swUpdate来侦听SW的更新,并在有新版本可用时进行更新。 Github Diff
// src/app/app.component.ts import {SwUpdate} from "@angular/service-worker";... Constructor (..., public swUpdate SWUpdate,)...ngOnInit() {
if (true) {
// check service worker to see if new version of app is available
if (this.swUpdate.isEnabled) {
this.swUpdate.available.subscribe(() =>; {
const snackBarRef = this.snackBar.open('New version available', 'Load New Version');snackBarRef.onAction().subscribe(
() =>; {
location.reload();}); }); } }}
Rebuild and reserve your application
重建并保留您的应用程序
To see the effect of service worker, we should deploy it to a real website. I like Firebase Hosting. You can take a web app from your localhost to a live website in less than 5 minutes with a few simple steps. I’ve been doing this for almost 2 years now and I still get impressed with how easy the process is. Lately, I have also been playing around with AWS S3 Static website hosting. This is another good alternative you can look into:
要查看服务人员的效果,我们应该将其部署到真实的网站上。 我喜欢Firebase Hosting。 您只需几个简单的步骤,就可以在不到5分钟的时间内将Web应用程序从本地主机转移到实时网站。 我这样做已经将近两年了,但我仍然对该过程的简易性印象深刻。 最近,我也一直在玩AWS S3 Static网站托管。 这是您可以研究的另一个不错的选择:
Create a google account
创建一个谷歌帐户
Create A firebase account and a firebase project
创建一个Firebase帐户和一个Firebase项目
install firebase tools globally: npm install -g [email protected]
全局安装firebase工具: npm install -g [email protected]
Log in to firebase: firebase login
登录Firebase: firebase login
Initialize Firebase Repo: firebase init
初始化Firebase Repo: firebase init
Deploy! Firebase deploy
部署! Firebase deploy
That’s it! Congratulations you now have a website that can work without the internet.
而已! 恭喜您,现在有了一个无需互联网即可运行的网站。
I’ve written previously about why I strongly believe that startups and companies should design their technology products as progressive web apps instead of mobile apps. My core arguments being:
我写 之前为什么我坚信,创业公司和企业渐进的网络应用程序的移动应用程序,而不是应该设计自己的技术产品。 我的核心观点是:
Having to maintain 2 separate Android and IOS codebases is a pain: 2 sets of users, 2 sets of developers, 2 sets of problems. (Things like Flutter and Ionic are cool but I don’t believe they address the fundamental issue of 2 separate codebases.)
不得不维护2个单独的Android和IOS代码库是一件很痛苦的事情:2套用户,2套开发人员,2套问题。 (诸如Flutter和Ionic之类的东西很酷,但我认为它们不能解决2个独立代码库的根本问题。)
Some of the core arguments against web apps include things like:
针对Web应用程序的一些核心论点包括:
With features like service workers, I have just shown how we can enable websites to work offline. Progressive web apps also enable push notifications.
借助服务工作者等功能,我刚刚展示了如何使网站能够离线工作。 渐进式Web应用程序还可以启用推送通知 。
Native hardware features are still the one advantage which mobile apps have, though this is changing. Unless it’s mission critical for your app to have these native features, I strongly encourage startups and companies to consider looking into making their next app a progressive web app.
尽管这种情况正在发生变化 ,但本机硬件功能仍然是移动应用程序具有的一项优势。 除非对您的应用程序具有这些本机功能至关重要,否则我强烈建议初创公司和公司考虑将其下一个应用程序升级为渐进式Web应用程序。
I think that the future of the internet will see more applications distributed through browsers and URLs than native apps and the app store. In an ironic case of history repeating itself, this is actually a throwback to the advent of the internet in the 90s when companies like Netscape and various “.com startups” were doing very well distributing their software through the web.
我认为,与本地应用程序和应用程序商店相比,互联网的未来将看到更多通过浏览器和URL分发的应用程序。 具有讽刺意味的是,历史重演,这实际上是对90年代互联网的出现的一次倒退,当时Netscape和各种“ .com初创公司”等公司都非常擅长通过网络分发其软件。
Wouldn’t it be awesome if other sites applied that same philosophy? Imagine if you’re like me and you have an hour plus commute to work every day. Forget about wifi, they don’t even have cellular service on the subway.
如果其他网站也采用相同的理念,那岂不是很棒吗? 想象一下,如果您像我一样,每天都有一个小时的上下班时间。 忘了wifi,他们甚至在地铁上都没有蜂窝服务。
Now suppose I want to buy Bluetooth headphones and I want to read some Amazon reviews before I make my decision. Wouldn’t it be awesome if I could cache the product details for the items in my shopping cart and read the reviews on my way to work? Then by the time I get to work, I can just buy the item I want.
现在,假设我想购买蓝牙耳机,并且想在做出决定之前先阅读一些亚马逊的评论。 如果我可以在购物车中缓存商品的产品详细信息并阅读上班方式的评论,那会很棒吗? 然后,当我开始工作时,我就可以购买想要的东西。
Or imagine you’re on the plane for a quick flight from Toronto to Ottawa. You load up the NY Times to catch up on morning news but the site gives the famous “Google dinosaur”. In an ideal world, the NY Times should cache the top 5 most popular articles. This allows users to read the articles and leave comments offline. The comments can be synced when they connect back to the internet.
或想像一下您正在乘飞机从多伦多飞往渥太华的快速航班。 您加载《纽约时报》以赶上早间新闻,但该网站提供了著名的“ Google恐龙”。 在理想的世界中,《纽约时报》应该保存最受欢迎的前5名文章。 这使用户可以阅读文章并使评论保持脱机状态。 当评论重新连接到Internet时,它们可以同步。
Google Docs does this best. Google Docs is Microsoft Word, Powerpoint and Excel but better and built for Chrome. You don’t need the internet to use Microsoft Word. Because Google Docs runs in a web browser, you should be able to use Google Docs to access and edit your recent items. Which is exactly what Google Docs does well.
Google文档可以做到最好。 Google文档是Microsoft Word,Powerpoint和Excel,但更好,并且是为Chrome构建的。 您不需要互联网即可使用Microsoft Word。 由于Google文档在网络浏览器中运行,因此您应该能够使用Google文档来访问和编辑您的近期项目。 Google Docs恰好可以做到这一点。
I feel slightly proud of the fact that the great Amazon and NY Times websites need the internet to run. I am humble that little Atila.ca runs just fine with and without internet. ;) When the internet is down, you can still see featured scholarships, blog posts and other pieces of content.
我对出色的亚马逊和纽约时报网站需要互联网运行感到自豪。 抱歉 , 无论有没有互联网, Atila.ca都能正常运行。 ;)当互联网中断时,您仍然可以看到特色奖学金,博客文章和其他内容。
Okay, these are mostly #FirstWorldProblems. But another thing that gets me really excited about this technology, is building the internet for the next billion users. For people who have very slow or inconsistent internet connection.
好的,这些主要是#FirstWorldProblems。 但是让我真正为这项技术感到兴奋的另一件事是为下一个十亿用户建立互联网。 对于互联网连接非常缓慢或不一致的人。
For example, HospitalRun is an offline first application. It manages hospitals in the developing world. These are places where intermittent connectivity is a fact of life. It allows records to be carried to remote clinics, where there may be no internet. It then syncs those records when there is. (h/t jonbellah.com)
例如, HospitalRun是一个脱机优先应用程序。 它管理着发展中国家的医院。 在这些地方,断断续续的连接已成为现实。 它允许将记录传送到可能没有互联网的远程诊所。 然后,如果有的话,它将同步那些记录。 (h / t jonbellah.com )
At Atila, one of our projects is increasing access to scholarships for students from developing countries. So it would be awesome if they could seamlessly read sample essays and work on their scholarship applications even if they lived in places with a poor internet connection.
在阿提拉(Atila),我们的项目之一是增加发展中国家学生获得奖学金的机会。 因此,即使他们生活在互联网连接较差的地方,他们也可以无缝阅读示例文章并从事其奖学金申请,真是太棒了。
I personally find the idea of service workers and offline-first web applications very fascinating. Simple technologies with the ability to fundamentally change the day to day habits of billions of people are why I chose to study software engineering and why I love this field. I’m really excited to not just see how the future of the internet will unfold but also help build the future of the internet and how we will interact it. The future is already here folks. Thanks for reading.
我个人觉得服务工作者和脱机优先的Web应用程序的想法非常有趣。 简单的技术能够根本改变数十亿人的日常习惯,这就是为什么我选择学习软件工程以及为什么我喜欢这个领域的原因。 不仅看到互联网的未来将如何发展,而且还能帮助建立互联网的未来以及我们如何进行互动,我感到非常兴奋。 未来已经在这里。 谢谢阅读。
Angular Official Service Worker Documentation
Angular公务员资料
Angular University: Angular Service Workers
Angular大学:Angular服务人员
Add Service Worker to Existing Angular App
将Service Worker添加到现有的Angular App
Angular Firebase — Deploying an Angular App to Firebase
Angular Firebase —将Angular应用程序部署到Firebase
翻译自: https://www.freecodecamp.org/news/how-to-build-websites-that-work-without-internet-using-angular-and-service-workers-lets-keep-in-42e846afa455/
angular 模块构建