이전에 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로 변경
명령어를 수동으로 실행하거나 npm scripts
기반 빌드 프로세스의 일부로 sw-precache
명령줄 인터페이스를 사용하는 개발자는 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 노드 모듈로 이동
gulp
/Grunt
워크플로의 일부로 또는 맞춤 node
빌드 스크립트 내에서 sw-precache
용 node
API를 사용하는 개발자는 workbox-build
node
모듈로 전환하여 이전할 수 있습니다.
workbox-build
모듈의 generateSW()
함수는 sw-precache
모듈의 write()
함수와 가장 일치합니다. 한 가지 중요한 차이점은 generateSW()
가 항상 프로미스를 반환하는 반면 이전 write()
함수는 콜백과 프로미스 기반 인터페이스를 모두 지원했다는 것입니다.
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
에서 제공하는 것과 동일한 서비스 워커를 가져올 수 있습니다.
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에서 문제를 열어 알려주세요.