以前に sw-precache
や sw-toolbox
を使用していたデベロッパーは、Workbox ファミリーのライブラリに簡単にアップグレードできます。Workbox にアップグレードすると、デバッグ機能とデベロッパーのエルゴノミクスが改善され、拡張可能な最新の Service Worker エクスペリエンスを提供できるようになります。
既存の構成に対する変更
次のいずれかのオプションで構成された 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,
},
},
}],
非推奨になったオプション
Express スタイルのワイルドカード ルートはサポートされなくなりました。runtimeCaching
構成または sw-toolbox
で直接 Express スタイルのワイルドカード ルートを使用していた場合は、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 node モジュールへ
gulp
/Grunt
ワークフローの一部として、またはカスタム node
ビルド スクリプト内で sw-precache
の node
API を使用しているデベロッパーは、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 から workbox-sw に移行する
sw-precache
の runtimeCaching
オプションを介して暗黙的に使用するのではなく、sw-toolbox
を直接使用している場合、Workbox への移行で同等の動作を得るには、いくつかの手動調整が必要になります。詳細については、workbox-routing
モジュールと workbox-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 で問題を報告してください。