为什么
开发 Web App 项目,项目一旦处于网络离线情况,就没法访问了。
我们希望给项目提供离线体验。
是什么
渐进式网络应用程序(progressive web application - PWA):是一种可以提供类似于 native app(原生应用程序) 体验的 Web App 的技术。
其中最重要的是,在 离线(offline) 时应用程序能够继续运行功能。
内部通过 Service Workers 技术实现的
npm i workbox-webpack-plugin -D
webpack.config.js(生产环境)
- const WorkboxPlugin = require("workbox-webpack-plugin");
- module.exports = {
- plugins: [
- new WorkboxPlugin.GenerateSW({
- // 这些选项帮助快速启用 ServiceWorkers
- // 不允许遗留任何“旧的” ServiceWorkers
- clientsClaim: true,
- skipWaiting: true,
- }),
- ]
- }
mian.js
- if ('serviceWorker' in navigator) {
- window.addEventListener('load', () => {
- navigator.serviceWorker.register('/service-worker.js').then(registration => {
- console.log('SW registered: ', registration);
- }).catch(registrationError => {
- console.log('SW registration failed: ', registrationError);
- });
- });
- }
npm run build
直接打开index.html
提示
因为我们打开的访问路径是:http://127.0.0.1:5500/dist/index.html
。此时页面会去请求 service-worker.js
文件,请求路径是:http://127.0.0.1:5500/service-worker.js
,这样找不到会 404。
实际 service-worker.js
文件路径是:http://127.0.0.1:5500/dist/service-worker.js
。
解决方案
npm i serve -g
运行命令要部署的目录
server dist
再次运行 npm run build
来构建包含注册代码版本的应用程序。访问 http://localhost:3000
并查看 console 控制台。在那里你应该看到:
总结:
core-js兼容比较差