如何用 Vanilla JavaScript 构建 PWA

这是一个关于创建一个进步式Web应用程序(PWA)的三部分系列的第一部分,该系列利用Web Push API和Cron-schedule. 在本文中,我们将涵盖基本内容:应用程序的前端,Web应用程序宣言和服务工作者方面,我们将只使用纯粹的JavaScript来实现这一点。

我们正在建设什么

在回家的路上,我对自己说:`我是开发人员,我自动化任务,让我们构建一个应用程序来帮助我服用我的药丸。

我们将建立一个简单的进步Web应用程序(PWA),它会提醒我每天服用药丸。

我们的应用程序将有一个由Express.js驱动的Web服务器。Express将向订阅推送通知的客户端推送通知。

步骤一:PWA

我们正在构建的应用程序必须提醒我们服用药丸,即使浏览器没有打开,所以我们需要一个 进步Web App

得到明顯的起來和準備

我的第一个步骤是创建一个PWA,使用这个生成器(https://app-manifest.firebaseapp.com/)生成一个宣言。这个工具将创建你的manifest.json文件,其中包含有关您的应用程序的所有基本信息。

只需在我们项目的根部解密文件夹中的所有内容,我们将称之为公共

 1[label Module: public/manifest.json]
 2 "name": "Temporas",
 3  "short_name": "Temporas",
 4  "theme_color": "#222831",
 5  "background_color": "#ffad17",
 6  "display": "standalone",
 7  "Scope": "",
 8  "start_url": "/index.html",
 9  "icons": [
10    // A lot of icons
11  ]

PWA 依靠 服务工作者。服务工作者是小程序,一旦它们被注册独立于你的JavaScript代码的其余部分,就会运行。


现在让我们创建我们的前端并注册我们的服务工人:

 1[label Module: public/index.html]
 2<!DOCTYPE html>
 3<head>
 4  <meta name='viewport' content='width=device-width, initial-scale=1'>
 5  <meta name="theme-color" content="#222831">
 6  <link rel='manifest' href='./manifest.json'>
 7
 8  <script>
 9    // Registering our Service worker
10    if('serviceWorker' in navigator) {
11      navigator.serviceWorker.register('sw.js', { scope: './' })
12    }
13  </script>
14</head>
15<body>
16  <div class="hero">
17    <h1>Temporas</h1>
18    <h2>Take your medicine my friend</h2>
19    <div id="status"></div>
20    <button id="unsubscribe">unsubscribe</button>
21  </div>
22</body>

我们现在离有一个可安装的Web应用程序很远,让我们创建我们的服务工作者:

 1[label Module: public/sw.js]
 2const cacheName = 'Temporas';
 3
 4// Cache all the files to make a PWA
 5self.addEventListener('install', e => {
 6  e.waitUntil(
 7    caches.open(cacheName).then(cache => {
 8      // Our application only has two files here index.html and manifest.json
 9      // but you can add more such as style.css as your app grows
10      return cache.addAll([
11        './',
12        './index.html',
13        './manifest.json'
14      ]);
15    })
16  );
17});
18
19// Our service worker will intercept all fetch requests
20// and check if we have cached the file
21// if so it will serve the cached file
22self.addEventListener('fetch', event => {
23  event.respondWith(
24    caches.open(cacheName)
25      .then(cache => cache.match(event.request, { ignoreSearch: true }))
26      .then(response => {
27        return response || fetch(event.request);
28      })
29  );
30});

✨✨ We have a PWA ✨✨

设置 Express.js

如果您在浏览器中打开/public/index.html,则 PWA 将无法工作,我们必须从 Web 服务器服务我们的内容。

首先,让我们在我们的命令行中设置东西,在您的根文件夹中运行:

1$ npm init
2$ npm install express body-parser
3$ touch app.js

package.json中,将脚本字段替换为:

1"scripts": {
2  "test": "echo \"Error: no test specified\" && exit 1",
3  "start": "node app.js"
4}

现在,让我们人口我们的应用程序:

 1[label Module: app.js]
 2const bodyParser = require('body-parser');
 3const express = require('express');
 4const app = express();
 5const port = 3000;
 6
 7// We want to use JSON to send post request to our application
 8app.use(bodyParser.json());
 9
10// We tell express to serve the folder public as static content
11app.use(express.static('public'));
12
13app.get('/public');
14
15app.listen(port, () => console.log(`Listening on port ${port}!`));

现在你可以运行 npm run start. 转到 http://localhost:3000,杀死服务器. 重新加载 http://localhost:3000并应用程序将看起来像它仍然工作! 您甚至可以关闭您的笔记本电脑并返回该端口的网页。

我强烈建议在开发新功能时禁用服务人员的缓存机制,这可能会引起一些混淆。

<$>[注意] 这是一个很好的帖子如果你想了解有关设置快递服务器的更多信息。

查看您的 PWA

要测试您的 PWA,我强烈建议使用 Lighthouse 扩展来查看一切是否正常工作. 另外,请记住,当部署您的应用程序到 Web 时,它需要通过 HTTPS 进行服务以被视为 PWA 并可作为应用程序安装。

您可以在此 GitHub 存储库中找到所有代码。

Published At
Categories with 技术
Tagged with
comments powered by Disqus