简体   繁体   English

无法将动态生成的可缓存链接数组传递给Service Worker

[英]Unable to pass a dynamically generated array of cacheable links to Service Worker

How do I pass a programmatically populated array of links to a service worker script for caching? 如何将程序填充的链接数组传递给Service Worker脚本进行缓存?

I am generating the array in cachelist.js like this: 我在cachelist.js中生成数组,如下所示:

const fs = require('fs');
const path = require('path');
require('dotenv').config();

var cachedItems = ['/'];
function walkSync(currentDirPath, callback) {
    fs.readdirSync(currentDirPath).forEach(function (name) {
        var filePath = path.join(currentDirPath, name);
        var stat = fs.statSync(filePath);
        if (stat.isFile()) {
            callback(filePath, stat);
        } else if (stat.isDirectory()) {
            walkSync(filePath, callback);
        }
    });
}

walkSync('./pages/', function(filePath, stat) {
  cachedItem = filePath.substr(5);
  if(cachedItem.indexOf('_') == -1) {
    cachedItems.push(cachedItem);
  }
});

module.exports = { cachedItems };

And then I'm trying to use this cachedItems array in /offline/serviceWorker.js as follows: 然后,我尝试在/offline/serviceWorker.js中使用此cachedItems数组,如下所示:

const URLSTOCACHE = require("../cachelist.js");
const CACHE_NAME = "version-0.0.46";

// Call install event
self.addEventListener("install", e => {
  e.waitUntil(
    caches
    .open(CACHE_NAME)
    .then(cache => cache.addAll(URLSTOCACHE))
    .then(() => self.skipWaiting())
  );
});

// Call fetch event
self.addEventListener("fetch", e => {
  e.respondWith(
    fetch(e.request).catch(() => caches.match(e.request))
  )
});

However, this fails with an " Uncaught ReferenceError: require is not defined. " Any workaround? 但是,此操作失败,并显示“ Uncaught ReferenceError:未定义。 ”是否有任何解决方法?

require isn't a built-in browser-side utility. require不是内置的浏览器端实用程序。 There are various libraries (like RequireJS) and bundlers (which rewrite the require call), but unless you're using one of those, you can't use require browser-side. 有各种各样的库(例如RequireJS)和捆绑器(它们重写了require调用),但是除非您使用其中之一,否则不能使用require浏览器端。

If your goal is to read that file in the service worker and add the URLs in it to the cache, use fetch to load it, and then use thme in addAll . 如果您的目标是在Service Worker中读取该文件并将其中的URL添加到缓存中,请使用fetch加载该文件,然后在addAll使用addAll

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM