Skip to content

Instantly share code, notes, and snippets.

@numbfall
Last active May 6, 2019 04:54
Show Gist options
  • Save numbfall/878455fa1dbfaf55dc8bf7ebe06af8d4 to your computer and use it in GitHub Desktop.
Save numbfall/878455fa1dbfaf55dc8bf7ebe06af8d4 to your computer and use it in GitHub Desktop.
Workbox rollup.js bundle
<!-- Load service worker in the navigator -->
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/serviceworker.js');
});
}
</script>
// get rollup and workbox packages
"devDependencies": {
"rollup": "^1.11.0",
"rollup-plugin-node-resolve": "^4.2.3",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-terser": "^4.0.4",
"workbox-cacheable-response": "^4.3.1",
"workbox-expiration": "^4.3.1",
"workbox-precaching": "^4.3.1",
"workbox-routing": "^4.3.1",
"workbox-strategies": "^4.3.1"
},
// config file for rollup
import resolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import {terser} from 'rollup-plugin-terser';
module.exports = {
input: 'assets/js/serviceworker.js', // change based on project
output: {
file: 'static/serviceworker.js', // change based on porject
format: 'iife' // i have no idea if we should use 'iife' or 'cjs' for service workers
},
plugins: [
resolve(),
replace({
'process.env.NODE_ENV': JSON.stringify('production') // fix for 'process' from a function error
}),
terser()
]
};
// main workbox service worker file to build bindle from
import {registerRoute} from 'workbox-routing/registerRoute.mjs';
import {CacheFirst} from 'workbox-strategies/CacheFirst.mjs';
import {StaleWhileRevalidate} from 'workbox-strategies/StaleWhileRevalidate.mjs';
import {Plugin as ExpirationPlugin} from 'workbox-expiration/Plugin.mjs';
import {Plugin as CacheableResponsePlugin} from 'workbox-cacheable-response/Plugin.mjs';
registerRoute(
/\.(?:png|jpg|jpeg|svg|gif)$/,
new CacheFirst({
cacheName: 'image-cache',
plugins: [
new ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 7 * 24 * 60 * 60,
}),
],
})
);
registerRoute(
/^https:\/\/fonts\.googleapis\.com/,
new StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets',
}),
);
registerRoute(
/^https:\/\/fonts\.gstatic\.com/,
new CacheFirst({
cacheName: 'google-fonts-webfonts',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 10,
}),
],
}),
);
registerRoute(
new RegExp('/'),
new StaleWhileRevalidate({
cacheName: 'website-cache',
plugins: [
new ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 7 * 24 * 60 * 60,
}),
],
}),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment