Commit 221db4af authored by Oleksii Savran's avatar Oleksii Savran

ServiceWorker

parent a22c4146
......@@ -11,6 +11,7 @@ const GitRevisionPlugin = require('git-revision-webpack-plugin');
const gitRevisionPlugin = new GitRevisionPlugin();
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const ReactLoadable = require('react-loadable/webpack');
const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin');
const fs = require('fs');
// devserver configuration
......@@ -213,6 +214,9 @@ module.exports = {
name: 'vendor',
minChunks: Infinity
}),*/
new ServiceWorkerWebpackPlugin({
entry: path.join(__dirname, '../src/sw/sw.ts'),
}),
// keep only required moment.js locales
new MomentLocalesPlugin({
localesToKeep: ['ar', 'es', 'fr'],
......
......@@ -24,6 +24,7 @@ import rootReducer from 'core/reducer';
// utilities
import { log } from '@gringlobal/client/utilities/debug';
import { reconfigureServiceAxios } from '@gringlobal/client/service';
import { registerSW } from 'sw/registerSW';
// ui
import { routes } from 'ui/routes';
import renderRoutes from '@gringlobal/client/ui/renderRoutes';
......@@ -121,3 +122,5 @@ if (__PRELOADED_STATE__ === undefined) {
);
});
}
registerSW();
......@@ -132,6 +132,7 @@
"roboto-fontface": "^0.10.0",
"sass-loader": "^8.0.2",
"script-ext-html-webpack-plugin": "^2.1.4",
"serviceworker-webpack-plugin": "^1.0.1",
"style-loader": "^1.2.1",
"stylelint": "^13.5.0",
"terser-webpack-plugin": "^3.0.3",
......
import runtime from 'serviceworker-webpack-plugin/lib/runtime';
export const registerSW = () => {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
runtime.register();
}
};
// eslint-disable-next-line spaced-comment
/// <reference lib="webworker" />
// https://github.com/oliviertassinari/serviceworker-webpack-plugin/blob/master/docs/src/sw.js
const IS_DEBUG = false;
// 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 CACHE_NAME = new Date().toISOString();
let assetsToCache = [...assets, './'];
assetsToCache = assetsToCache.map((path) => {
return new URL(path, global.location.toString()).toString();
});
// When the service worker is first added to a computer.
self.addEventListener('install', (event) => {
// Perform install steps.
if (IS_DEBUG) {
console.log('[SW] Install event');
}
// Add core website files to cache during serviceworker installation.
event.waitUntil(
global.caches
.open(CACHE_NAME)
.then((cache) => {
return cache.addAll(assetsToCache);
})
.then(() => {
if (IS_DEBUG) {
console.log('Cached assets: main', assetsToCache);
}
})
.catch((error) => {
console.error(error);
throw error;
})
)
});
// After the install event.
self.addEventListener('activate', (event) => {
if (IS_DEBUG) {
console.log('[SW] Activate event');
}
// Clean the caches
event.waitUntil(
global.caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
// Delete the caches that are not the current one.
if (cacheName.indexOf(CACHE_NAME) === 0) {
if (IS_DEBUG) {
console.log(`[SW] use cache ${cacheName}`);
}
return null;
}
if (IS_DEBUG) {
console.log(`[SW] delete cache ${cacheName}`);
}
return global.caches.delete(cacheName);
})
)
})
)
});
// self.addEventListener('message', (event) => {
// switch (event.data.action) {
// case 'skipWaiting':
// if (self.skipWaiting) {
// self.skipWaiting();
// self.clients.claim();
// }
// break;
// default:
// break;
// }
// });
self.addEventListener('fetch', (event) => {
const request = event.request;
// Ignore not GET request.
if (request.method !== 'GET') {
if (IS_DEBUG) {
console.log(`[SW] Ignore non GET request ${request.method}`);
}
return;
}
const requestUrl = new URL(request.url);
// Ignore difference origin.
if (requestUrl.origin !== location.origin) {
if (IS_DEBUG) {
console.log(`[SW] Ignore difference origin ${requestUrl.origin}`);
}
return;
}
const resource = global.caches.match(request).then((response) => {
if (response) {
if (IS_DEBUG) {
console.log(`[SW] fetch URL ${requestUrl.href} from cache`);
}
return response;
}
// Load and cache known assets.
return fetch(request)
.then((responseNetwork) => {
if (!responseNetwork || !responseNetwork.ok) {
if (IS_DEBUG) {
console.log(
`[SW] URL [${requestUrl.toString()}] wrong responseNetwork: ${responseNetwork.status} ${responseNetwork.type}`
)
}
return responseNetwork;
}
if (IS_DEBUG) {
console.log(`[SW] URL ${requestUrl.href} fetched`);
}
const responseCache = responseNetwork.clone();
global.caches
.open(CACHE_NAME)
.then((cache) => {
return cache.put(request, responseCache);
})
.then(() => {
if (IS_DEBUG) {
console.log(`[SW] Cache asset: ${requestUrl.href}`);
}
});
return responseNetwork;
})
.catch(() => {
// User is landing on our page.
if (event.request.mode === 'navigate') {
return global.caches.match('./');
}
return null;
})
});
event.respondWith(resource);
});
......@@ -13474,6 +13474,13 @@ serve-static@1.14.1:
parseurl "~1.3.3"
send "0.17.1"
serviceworker-webpack-plugin@^1.0.1:
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==
dependencies:
minimatch "^3.0.4"
set-blocking@^2.0.0, set-blocking@~2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7"
......
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