Commit 8dab821f authored by Matija Obreza's avatar Matija Obreza
Browse files

DRAFT: service-worker.js

- Don't cache too much stuff!
parent ae52fb6b
......@@ -216,10 +216,6 @@ module.exports = {
minChunks: Infinity
}),*/
new ServiceWorkerWebpackPlugin({
entry: path.join(__dirname, '../src/sw/sw.ts'),
}),
// keep only required moment.js locales
new MomentLocalesPlugin({
localesToKeep: [ 'ar', 'es', 'fr' ],
......@@ -303,6 +299,12 @@ module.exports = {
],
}),
new ServiceWorkerWebpackPlugin({
entry: path.join(__dirname, '../src/sw/sw.ts'),
filename: 'service-worker.js',
excludes: [ '**/*.html', '**/COMMITHASH', '**/VERSION', '**/**.LICENSE.txt', '**/*.map', './', '/', '*.html' ],
}),
new ReactLoadable.ReactLoadablePlugin({
filename: 'react-loadable.json',
}),
......
......@@ -136,3 +136,5 @@ if (__PRELOADED_STATE__ === undefined) {
);
});
}
registerSW();
......@@ -11,6 +11,7 @@
"build:server": "cross-env NODE_OPTIONS=--max_old_space_size=8192 NODE_ENV=production webpack --config config/server.config.js",
"build:client": "cross-env NODE_OPTIONS=--max_old_space_size=8192 NODE_ENV=production webpack --config config/webpack-production.config.js",
"start:dev": "lerna run i18nGenerate && cross-env NODE_OPTIONS=--max_old_space_size=8192 webpack-dev-server --config config/webpack-development.config.js",
"start:webpack-prod": "lerna run i18nGenerate && cross-env NODE_OPTIONS=--max_old_space_size=8192 webpack-dev-server --config config/webpack-production.config.js",
"start:prod": "yarn build && yarn run:ssr",
"run:ssr": "cd target/app/server && node server.js",
"build:debug": "lerna run i18nGenerate && yarn run build:client:debug && yarn run build:server:debug",
......
import runtime from 'serviceworker-webpack-plugin/lib/runtime';
export const registerSW = () => {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
runtime.register();
const USE_SW = true || process.env.NODE_ENV === 'production';
export const registerSW = (): void => {
if (USE_SW && 'serviceWorker' in navigator
&& (window.location.protocol === 'https:' || window.location.hostname === 'localhost')) {
if (runtime) {
console.log('Registering SW');
runtime.register();
} else {
console.log('Runtime is not defined!');
}
}
};
}
......@@ -2,22 +2,37 @@
/// <reference lib="webworker" />
// https://github.com/oliviertassinari/serviceworker-webpack-plugin/blob/master/docs/src/sw.js
const IS_DEBUG = false;
// force debug mode
const IS_DEBUG = true; // || process.env.NODE_ENV !== 'production';
// When the user navigates to your site,
// the browser tries to redownload the script file that defined the service
// worker in the background.
// If there is even a byte's difference in the service worker file compared
// to what it currently has, it considers it 'new'.
const { assets } = (global as any).serviceWorkerOption;
const swo = (global as any).serviceWorkerOption;
const { assets, ...otherOptions } = swo;
if (IS_DEBUG) {
console.log('Other options', JSON.stringify(otherOptions));
}
const CACHE_NAME = new Date().toISOString();
if (IS_DEBUG) {
console.log(`Using ${CACHE_NAME} as cache`);
}
let assetsToCache = [...assets, './'];
let assetsToCache = [...assets ];
if (IS_DEBUG) {
console.log('Assets', JSON.stringify(assetsToCache));
}
assetsToCache = assetsToCache.map((path) => {
return new URL(path, global.location.toString()).toString();
});
if (IS_DEBUG) {
console.log('Assets mapped', JSON.stringify(assetsToCache));
}
// When the service worker is first added to a computer.
self.addEventListener('install', (event) => {
......@@ -49,6 +64,7 @@ self.addEventListener('install', (event) => {
self.addEventListener('activate', (event) => {
if (IS_DEBUG) {
console.log('[SW] Activate event');
console.log('Other options', JSON.stringify(otherOptions));
}
// Clean the caches
......@@ -89,7 +105,7 @@ self.addEventListener('activate', (event) => {
self.addEventListener('fetch', (event) => {
const request = event.request;
// Ignore not GET request.
// Handle only GET requests
if (request.method !== 'GET') {
if (IS_DEBUG) {
console.log(`[SW] Ignore non GET request ${request.method}`);
......@@ -99,10 +115,10 @@ self.addEventListener('fetch', (event) => {
const requestUrl = new URL(request.url);
// Ignore difference origin.
// Ignore other origins
if (requestUrl.origin !== location.origin) {
if (IS_DEBUG) {
console.log(`[SW] Ignore difference origin ${requestUrl.origin}`);
console.log(`[SW] Ignoring other origin ${requestUrl.origin}`);
}
return;
}
......@@ -110,7 +126,7 @@ self.addEventListener('fetch', (event) => {
const resource = global.caches.match(request).then((response) => {
if (response) {
if (IS_DEBUG) {
console.log(`[SW] fetch URL ${requestUrl.href} from cache`);
console.log(`[SW] fetch URL ${requestUrl.href} from cache ${CACHE_NAME}`);
}
return response;
......@@ -122,7 +138,7 @@ self.addEventListener('fetch', (event) => {
if (!responseNetwork || !responseNetwork.ok) {
if (IS_DEBUG) {
console.log(
`[SW] URL [${requestUrl.toString()}] wrong responseNetwork: ${responseNetwork.status} ${responseNetwork.type}`
`[SW] URL [${requestUrl.toString()}] no responseNetwork: ${responseNetwork.status} ${responseNetwork.type}`
)
}
......@@ -133,26 +149,41 @@ self.addEventListener('fetch', (event) => {
console.log(`[SW] URL ${requestUrl.href} fetched`);
}
const responseCache = responseNetwork.clone();
{
if (IS_DEBUG) {
console.log(`[SW] may add ${requestUrl.href} to cache!`);
}
return responseNetwork;
global.caches
.open(CACHE_NAME)
.then((cache) => {
return cache.put(request, responseCache);
})
.then(() => {
if (IS_DEBUG) {
console.log(`[SW] Cache asset: ${requestUrl.href}`);
}
});
// Consider caching the response
const responseCache = responseNetwork.clone();
global.caches
.open(CACHE_NAME)
.then((cache) => {
if (IS_DEBUG) {
console.log(`[SW] adding to cache ${requestUrl.href}!!!`);
}
return cache.put(request, responseCache);
})
.then(() => {
if (IS_DEBUG) {
console.log(`[SW] Cache asset: ${requestUrl.href}`);
}
});
}
return responseNetwork;
})
.catch(() => {
.catch((err) => {
// User is landing on our page.
if (event.request.mode === 'navigate') {
return global.caches.match('./');
if (IS_DEBUG) {
console.log(`[SW] caught error accessing ${requestUrl.href}`, err);
console.log('[SW] event', JSON.stringify(event));
}
// if (event.request.mode === 'navigate') {
// return global.caches.match('./');
// }
return null;
})
......
......@@ -14213,7 +14213,7 @@ serve-static@1.14.1:
parseurl "~1.3.3"
send "0.17.1"
 
serviceworker-webpack-plugin@^1.0.1:
serviceworker-webpack-plugin@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/serviceworker-webpack-plugin/-/serviceworker-webpack-plugin-1.0.1.tgz#481863288487e92da01d49745336c72ef8a6136b"
integrity sha512-VgDEkZ3pA0HajsRaWtl5w6bLxAXx0Y+4dm7YeTcIxVmvC9YXvstex38HOBDuYETeDS5fUlBy/47gC0QYBrG0nw==
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment