從 sw-precache 或 sw-toolbox 遷移

先前曾使用 sw-precache 和/或 sw-toolbox 的開發人員,對 Workbox 系列程式庫的升級路徑有直觀的升級路徑。升級至 Workbox 將提供現代化的可擴充性服務工作人員體驗,包括改善偵錯能力和開發人員人體工學。

修改現有設定

如果您使用的 sw-precache 是透過下列任一選項進行設定,在遷移至 Workbox 時,請將下列變更納入考量。

已重新命名的選項

dynamicUrlToDependencies 設定參數已重新命名為 templatedURLs

staticFileGlobs 設定參數已重新命名為 globPatterns

runtimeCaching 設定參數採用一組更新過的選項,與基礎 Workbox 模組中使用的名稱相對應。為說明已重新命名的項目,以下 sw-precache 設定:

runtimeCaching: [{
  urlPattern: /api/,
  handler: 'fastest',
  options: {
    cache: {
      name: 'my-api-cache',
      maxEntries: 5,
      maxAgeSeconds: 60,
    },
  },
}],

相當於以下 Workbox 設定:

runtimeCaching: [{
  urlPattern: /api/,
  // 'fastest' is now 'StaleWhileRevalidate'
  handler: 'StaleWhileRevalidate',
  options: {
    // options.cache.name is now options.cacheName
    cacheName: 'my-api-cache',
    // options.cache is now options.expiration
    expiration: {
      maxEntries: 5,
      maxAgeSeconds: 60,
    },
  },
}],

已淘汰的選項

不再支援速成式萬用字元路徑。如果您在 runtimeCaching 設定或直接使用 sw-toolbox 中使用快速樣式萬用字元路徑,請在使用 Workbox 時改用對等的規則運算式路徑。

sw-precache 遷移

從 sw-precache CLI 到 Workbox-cli

如果開發人員使用 sw-precache 指令列介面,無論是手動執行指令,還是在以 npm scripts 為基礎的建構程序中執行,他們都能發現使用 workbox-cli 模組是最輕鬆的遷移方式。安裝 workbox-cli 可讓您存取名為 workbox 的二進位檔。

雖然透過指令列旗標或設定檔支援設定 sw-precache CLI,但 workbox CLI 要求您在設定檔中必須提供所有設定選項,並使用 CommonJS module.exports

workbox CLI 支援多種不同的模式。(使用 workbox --help 即可查看所有通知)。不過,與 sw-precache 功能最相符的模式為 generateSW。所以,

$ sw-precache --config='sw-precache-config.js'

可以表示

$ workbox generateSW workbox-config.js

從 sw-precache 節點模組到 workbox-build 節點模組

如果開發人員使用 sw-precache 適用的 node API,不論是在 gulp/Grunt 工作流程中,或只在自訂 node 建構指令碼中,都可以改用 workbox-build node 模組進行遷移。

workbox-build 模組的 generateSW() 函式與 sw-precache 模組的 write() 函式最為相符。主要差異在於 generateSW() 一律會傳回 Promise,而舊版 write() 函式同時支援回呼和 Promise 型介面。

下方各行數的gulp用量

const swPrecache = require('sw-precache');
gulp.task('generate-service-worker', function () {
  return swPrecache.write('service-worker.js', {
    // Config options.
  });
});

可以變更為

const workboxBuild = require('workbox-build');
gulp.task('generate-service-worker', function () {
  return workboxBuild.generateSW({
    // Config options.
  });
});

從 sw-precache-webpack-plugin 到 Workbox Webpack 外掛程式

如果開發人員在 webpack 建構程序中使用 sw-precache-webpack-plugin,可以在 workbox-webpack-plugin 模組中切換至 GenerateSW 類別。

workbox-webpack-plugin 會直接與 Webpack 建構程序整合,且會針對特定編譯產生的所有資產「瞭解」。也就是說,在許多用途中,您無須額外設定即可依賴 workbox-webpack-plugin 的預設行為,並取得與 sw-precache-webpack-plugin 提供的對等 Service Worker。

const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const webpackConfig = {
  // ...
  plugins: [
    new SWPrecacheWebpackPlugin({
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
    }),
  ],
};

可以變更為

const {GenerateSW} = require('workbox-webpack-plugin');
const webpackConfig = {
  // ...
  plugins: [
    new GenerateSW({
      // Config options, if needed.
    }),
  ],
};

sw-toolbox 遷移

從手工 sw-toolbox 遷移至工作箱

如果您直接使用 sw-toolbox (而不是透過 sw-precacheruntimeCaching 選項以隱含方式使用),遷移至 Workbox 就需要手動進行調整,才能取得對等的行為。如要進一步瞭解相關資訊,請參閱 workbox-routingworkbox-strategies 模組的說明文件,瞭解相關資訊。

以下程式碼片段可協助您完成遷移作業。這段 sw-toolbox 代碼:

importScripts('path/to/sw-toolbox.js');

// Set up a route that matches HTTP 'GET' requests.
toolbox.router.get(
  // Match any URL that contains 'ytimg.com', regardless of
  // where in the URL that match occurs.
  /\.ytimg\.com\//,

  // Apply a cache-first strategy to anything that matches.
  toolbox.cacheFirst,

  {
    // Configure a custom cache name and expiration policy.
    cache: {
      name: 'youtube-thumbnails',
      maxEntries: 10,
      maxAgeSeconds: 30,
    },
  }
);

// Set a default network-first strategy to use when
// there is no explicit matching route:
toolbox.router.default = toolbox.networkFirst;

相當於以下 Workbox 代碼:

importScripts('path/to/workbox-sw.js');

workbox.routing.registerRoute(
  // Match any URL that contains 'ytimg.com'.
  // Unlike in sw-toolbox, in Workbox, a RegExp that matches
  // a cross-origin URL needs to include the initial 'https://'
  // as part of the match.
  new RegExp('^https://.*.ytimg.com'),

  // Apply a cache-first strategy to anything that matches.
  new workbox.strategies.CacheFirst({
    // Configuration options are passed in to the strategy.
    cacheName: 'youtube-thumbnails',
    plugins: [
      new workbox.expiration.ExpirationPlugin({
        maxEntries: 10,
        maxAgeSeconds: 30,
      }),
      // In Workbox, you must explicitly opt-in to caching
      // responses with a status of 0 when using the
      // cache-first strategy.
      new workbox.cacheableResponse.CacheableResponsePlugin({
        statuses: [0, 200],
      }),
    ],
  })
);

// Set a default network-first strategy to use when
// there is no explicit matching route:
workbox.routing.setDefaultHandler(new workbox.strategies.NetworkFirst());

取得協助

我們預期大多數遷移至 Workbox 的做法都很簡單。如果遇到本指南未涵蓋的問題,請前往 GitHub 開啟問題回報給我們。