$ vue init pwa my-project
$ cd my-project
$ npm i
// 기본적인 Service Worker 등록 방법 (자신의 코드)
navigator.serviceWorker
.register('./service-worker.js')
.then(function() {
console.log('Service Worker Registered');
});
// 기본적인 Service Worker 파일
// self는 ServiceWorkerGlobal Scope를 지칭
self.addEventListener('install', () => {
self.skipWaiting()
});
self.addEventListener('activate', () => {
self.clients.matchAll({ type: 'window' })
.then(windowClients => {
for (let windowClient of windowClients) {
// ...do someting!
windowClient.navigate(windowClient.url);
}
});
});
// in webpack.dev.conf.js
...
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true,
serviceWorkerLoader: `<script>
${fs.readFileSync(
path.join(__dirname,
'./service-worker-dev.js'),
'utf-8'
)}
</script>`
}),
...
]
// in service-worker-dev.js
self.addEventListener('install', () => {
self.skipWaiting()
});
self.addEventListener('activate', () => {
self.clients.matchAll({ type: 'window' })
.then(windowClients => {
for (let windowClient of windowClients) {
// ...do someting!
windowClient.navigate(windowClient.url);
}
});
});
// service worker caching in webpack.prod.conf.js
plugins: [
...
new SWPrecacheWebpackPlugin({
cacheId: 'CACHE_ID',
filename: 'service-worker.js',
staticFileGlobs: ['dist/**/*.{js,html,css}'],
minify: true,
stripPrefix: 'dist/'
})
...
]
// in service-worker-prod.js
...
window.addEventListener('load', function() {
if ('serviceWorker' in navigator &&
(window.location.protocol === 'https:'
|| isLocalhost)) {
navigator.serviceWorker
.register('service-worker.js')
.then(function(registration) {
// ...someting to do!
}).catch(function(e) {
console.error('err sw registration');
});
}
});
...
// API_CACHE_PATTERN은 캐시할 url
new SWPrecacheWebpackPlugin({
cacheId: 'seouldrinkerpwa',
filename: 'service-worker.js',
staticFileGlobs: ['dist/**/*.{js,html,css}'],
minify: true,
stripPrefix: 'dist/',
runtimeCaching: [{
urlPattern: API_CACHE_PATTERN,
handler: 'networkFirst',
}],
importScripts: [
'sw.js'
]
}),
// 이어서
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
},
{
from: path.resolve(__dirname, './sw.js'),
to: '',
ignore: ['.*']
}
])