如何在Vue js中编写PWA?

问题描述 投票:0回答:1

我曾经通过香草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的文件,因为我不习惯使用它

enter image description here

此文件包含以下内容

/* 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代码,或者在哪里可以做?另外我也不知道它是否可以在localhost上运行,因为我注意到它可以在生产环境中使用。

所以我的问题是,如何像在vue应用程序中使用Vanilla js一样编写PWA?要完成完整的自定义PWA,我应该采取什么步骤?

我可以不使用工作箱来做到这一点吗?

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

谢谢。

我曾经通过像这样的importScripts('/ src / js / idb.js')通过香草javascript编写pwa。 importScripts('/ src / js / utility.js'); const CACHE_STATIC_NAME ='static-v4'; const CACHE_DYNAMIC_NAME ='...

vue.js progressive-web-apps vue-pwa
1个回答
0
投票

[//我们中的大多数人都不会在任何项目中从头开始重做服务工作者,Workbox也是Vue CLI以外的Google Developers page中推荐的工具。

© www.soinside.com 2019 - 2024. All rights reserved.