【问题标题】:How to use injectManifest in Workbox with Parcel-bundler?如何在带有 Parcel-bundler 的 Workbox 中使用 injectManifest?
【发布时间】:2020-10-25 16:22:17
【问题描述】:

我正在使用 Workbox 为我的 PWA 构建一个服务工作者。

service-worker.js

import { registerRoute } from 'workbox-routing';
import { NetworkFirst } from 'workbox-strategies';
import { CacheFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import * as googleAnalytics from 'workbox-google-analytics';
import { precacheAndRoute } from 'workbox-precaching';

googleAnalytics.initialize();

registerRoute(
    ({ request }) => request.destination === 'script',
    new NetworkFirst()
);

registerRoute(
    // Cache style resources, i.e. CSS files.
    ({ request }) => request.destination === 'style',
    // Use cache but update in the background.
    new StaleWhileRevalidate({
        // Use a custom cache name.
        cacheName: 'css-cache',
    })
);

registerRoute(
    // Cache image files.
    ({ request }) => request.destination === 'image',
    // Use the cache if it's available.
    new CacheFirst({
        // Use a custom cache name.
        cacheName: 'image-cache',
        plugins: [
            new ExpirationPlugin({
                // Cache for a maximum of a week.
                maxAgeSeconds: 7 * 24 * 60 * 60,
            }),
        ],
    })
);

precacheAndRoute(self.__WB_MANIFEST);

if (process.env.NODE_ENV !== 'production') {
    console.log('This is a dev-only log message!');
}

有没有办法让 Parcel 在每次构建后只在 service worker 中注入最新版本的文件?

我的尝试

  1. 我尝试在节点脚本中使用 workbox-build,但每次运行 npm run build 时,它都会添加 dist/ 文件夹中存在的所有文件版本。

service-worker.js(当我使用 Node 脚本时)

// code skipped for brevity
precacheAndRoute([
{"revision":"78416d1f083fa1a898d17e20d741a462","url":"Share.332aebe4.js"},{"revision":"413f2ed8c0dcd51e3c01855ac307f6d2","url":"Share.77f580e5.js"},{"revision":"c95daa634502ca4a38e1822e7460688e","url":"style.0f60499b.css"},{"revision":"7f4b6e94999540101a2a7e5b4226080e","url":"style.78032849.css"}])

它们是同一文件的不同版本,但我只想要最新版本

  1. 我尝试使用parcel-plugin-sw-cache,但由于文档不足,无法弄清楚如何使用它。

【问题讨论】:

    标签: reactjs progressive-web-apps workbox parceljs


    【解决方案1】:

    parcel-plugin-sw-cache 在您更改时有效

    precacheAndRoute(self.__WB_MANIFEST);
    

    precacheAndRoute([]);
    

    另外,当您使用injectManifest方法时,您需要在package.json中提供"swSrc": "service-worker.js"(根据documentation

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 2022-07-13
      • 2019-06-29
      • 2021-07-07
      • 2019-08-17
      • 2020-12-27
      • 2021-07-07
      • 2021-10-27
      • 2021-04-19
      相关资源
      最近更新 更多