【问题标题】:How to write PWA in Vue js?如何在 Vue js 中编写 PWA?
【发布时间】:2020-08-05 23:04:26
【问题描述】:

我曾经像这样通过 vanilla javascript 编写 pwa

importScripts('/src/js/idb.js');
importScripts('/src/js/utility.js');

const CACHE_STATIC_NAME = 'static-v4';
const CACHE_DYNAMIC_NAME = 'dynamic-v2';
const STATIC_FILES = [
  '/',
  '/index.html',
  '/offline.html',
  '/src/js/app.js',
  '/src/js/feed.js',
  '/src/js/promise.js',
  '/src/js/fetch.js',
  '/src/js/idb.js',
  '/src/js/material.min.js',
  '/src/css/app.css',
  '/src/css/feed.css',
  '/src/images/main-image.jpg',
  'https://fonts.googleapis.com/css?family=Roboto:400,700',
  'https://fonts.googleapis.com/icon?family=Material+Icons',
  'https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.3.0/material.indigo-pink.min.css'
 ];

 self.addEventListener('install', function(e) {
    e.waitUntil(
      caches.open(CACHE_STATIC_NAME)
       .then(function(cache) {
           console.log('[Service Worker] Installing Service Worker ...');
              cache.addAll(STATIC_FILES);
       })
    );
 });

 self.addEventListener('activate', function(e) {
    console.log('[Service Worker] Activating Service Worker ...');

    // clear old cache
    e.waitUntil(
        caches.keys()
          .then(function(cachedKeys) {
              return Promise.all(cachedKeys.map(function(key) {
                  if(key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
                    return caches.delete(key);
                  }
              }))
          })
    );
// Tell the active service worker to take control of the page immediately.
    return self.clients.claim(); // to ensure that activating is correctly done
});

//After install, fetch event is triggered for every page request
self.addEventListener('fetch', function(event) {
  let url = 'https://pwa-training-4a918.firebaseio.com/posts.json';

  if(event.request.url === url) {
    event.respondWith( 
      fetch(event.request).then(res => {
          let clonedRes = res.clone();
          // in order to clear ol data if new data is different from the original one
          clearAllData('posts')
            .then(() => {
              return clonedRes.json()
            })
            .then(data => {
              for(let key in data) {
                writeData('posts', data[key])
              }
            });


          return res;
        })
      );
    // USE Cache only Strategy if the request is in the static Files
  } else if(STATIC_FILES.includes(event.request.url)) {
    event.respondWith(
      caches.match(event.request)
    ); 
  } else {
    event.respondWith(
      caches.match(event.request).then(response => {
        return response || fetch(event.request).then(response => {
          return caches.open(CACHE_DYNAMIC_NAME).then(cache => {
            cache.put(event.request, response.clone());
  
            return response;
          })
        })
      })
      .catch(err => {
        return caches.open(CACHE_STATIC_NAME).then(cache => {
          // i need to show offline page only if the failure is in the help Page
          // because it does not make any sence if i show this page in case of the failure in files like css 
          if(event.request.headers.get('accept').includes('text/html')) {
            return cache.match('/offline.html');
          }
        })
      })
    );
  }
});

但是当我尝试在 vuejs 应用程序中编写自己的应用程序时,我通过 vue add pwa 安装了 pwa,它为我创建了一个名为 registerServiceWorker.js 的文件,我不明白,因为我不习惯使用它

此文件包含以下内容

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}

我不知道如何在这里编写自己的 pwa 代码,或者在哪里可以这样做? 另外我不知道它是否可以在本地主机上工作,因为据我观察它在生产中工作

所以我的问题是,我如何像以前在 vue 应用程序中使用 vanilla js 那样编写 PWA?为了完成我的完整自定义 PWA,我应该执行哪些步骤?

我可以在不使用工作箱的情况下做到这一点吗?

如果有人可以帮助我,我将不胜感激。

提前致谢。

【问题讨论】:

    标签: vue.js progressive-web-apps vue-pwa


    【解决方案1】:

    我/(我们中的大多数人)不太可能在任何项目中从头开始重做 service worker,除了 Vue CLI,Workbox 也是 Google Developers 的page 推荐的工具。

    作为registerServiceWorker.js,这是您的应用程序中的服务工作者周期的样板,因为日志在您的应用程序流程中非常简单

    如果您仍想从头开始,我建议您阅读https://developers.google.com/web/fundamentals/primers/service-workers/ 以了解基本原理。我会推荐,因为service-worker 几乎是“我希望你知道你对你的应用做了什么,比如什么时候更新/缓存/离线时做/”

    【讨论】:

    • 我知道基础知识,但我很困惑 vue 应用程序中服务工作者的来源在哪里,以便对其进行修改或自定义。我应该修改registerServiceWorker.js 还是我对此感到真正困惑的地方。在某些情况下,我需要什么来选择某种缓存策略?如何以及在哪里可以做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 2021-05-07
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2020-02-15
    • 2018-01-12
    • 2019-12-09
    相关资源
    最近更新 更多