Skip to content

Commit bc060e4

Browse files
MT-3964 customize CRA SW caching policy (#55)
* customize cra sw caching policy * update sw template and build function * update workbox-build version
1 parent 7e3008e commit bc060e4

File tree

5 files changed

+1160
-11
lines changed

5 files changed

+1160
-11
lines changed

build-sw.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
const fs = require('fs-extra')
2+
const pathmodule = require('path')
3+
const workbox = require('workbox-build')
4+
const outputPath = 'build'
5+
6+
async function build() {
7+
const cwd = process.cwd();
8+
const pkgPath = `${cwd}/node_modules/workbox-sw/package.json`;
9+
const pkg = require(pkgPath);
10+
const readPath = `${cwd}/node_modules/workbox-sw/${pkg.main}`;
11+
let data = fs.readFileSync(readPath, 'utf8');
12+
let path = `${cwd}/${outputPath}/workbox-sw.js`;
13+
console.log(`Writing ${path}.`);
14+
fs.writeFileSync(path, data, 'utf8');
15+
data = fs.readFileSync(`${readPath}.map`, 'utf8');
16+
path = `${cwd}/${outputPath}/${pathmodule.basename(pkg.main)}.map`;
17+
console.log(`Writing ${path}.`);
18+
fs.writeFileSync(path, data, 'utf8');
19+
20+
const configString = fs.readFileSync('./src/config.ts', 'utf8');
21+
const configJSON = configString.replace('export', '');
22+
fs.writeFileSync('./build/config.js', configJSON);
23+
24+
await workbox.injectManifest({
25+
globDirectory: `./${outputPath}/`,
26+
globPatterns: ['**\/*.{html,js,css,png,jpg,json}'],
27+
globIgnores: ['sw-default.js', 'service-worker.js', 'workbox-sw.js', 'index.html'],
28+
swSrc: './src/sw-template.js',
29+
swDest: `./${outputPath}/sw-default.js`,
30+
}).then(_ => {
31+
console.log('Service worker generated.')
32+
})
33+
}
34+
35+
build();
36+

package.json

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,17 @@
2828
"react-scripts": "3.4.1",
2929
"serve": "^11.3.1",
3030
"sharethis-reactjs": "^1.5.0",
31-
"typescript": "^3.7.3"
31+
"typescript": "^3.7.3",
32+
"workbox-build": "^5.1.3"
3233
},
3334
"scripts": {
3435
"start": "EXTEND_ESLINT=true BROWSER=none react-scripts start",
35-
"build": "EXTEND_ESLINT=true GENERATE_SOURCEMAP=false INLINE_RUNTIME_CHUNK=true react-scripts build",
36+
"build": "EXTEND_ESLINT=true GENERATE_SOURCEMAP=false INLINE_RUNTIME_CHUNK=true react-scripts build && yarn sw",
3637
"test": "EXTEND_ESLINT=true react-scripts test",
3738
"eject": "react-scripts eject",
3839
"serve": "serve -c serve.json",
39-
"pseudo-translate": "node utils/pseudo-translate.js"
40+
"pseudo-translate": "node utils/pseudo-translate.js",
41+
"sw": "node build-sw.js"
4042
},
4143
"eslintConfig": {
4244
"extends": "react-app"

src/serviceWorker.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ export function register(config?: Config) {
2828
}
2929

3030
window.addEventListener('load', () => {
31-
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
31+
const swUrl = `${process.env.PUBLIC_URL}/sw-default.js`;
32+
// const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
3233

3334
if (isLocalhost) {
3435
// This is running on localhost. Let's check if a service worker still exists or not.

src/sw-template.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
importScripts('/workbox-sw.js');
2+
importScripts('/config.js');
3+
4+
workbox.core.skipWaiting();
5+
workbox.core.clientsClaim();
6+
self.__WB_MANIFEST;
7+
8+
// app-shell
9+
workbox.routing.registerRoute('/', new workbox.strategies.NetworkFirst());
10+
workbox.routing.registerRoute(/\.(?:js|css|html)$/, new workbox.strategies.NetworkFirst());
11+
12+
// webfont-cache
13+
const webFontHandler = new workbox.strategies.CacheFirst({
14+
cacheName: 'webfont-cache',
15+
plugins: [
16+
new workbox.expiration.ExpirationPlugin({maxEntries: 20}),
17+
new workbox.cacheableResponse.CacheableResponsePlugin({statuses: [0, 200]}),
18+
],
19+
});
20+
workbox.routing.registerRoute(/https:\/\/fonts.googleapis.com\/.*/, webFontHandler);
21+
workbox.routing.registerRoute(/https:\/\/fonts.gstatic.com\/.*/, webFontHandler);
22+
23+
// get-urls-cache
24+
const API = new RegExp('https:\/\/' + config.endpointURL + '\/.*');
25+
const apiHandler = new workbox.strategies.NetworkFirst({
26+
cacheName: 'get-urls-cache'
27+
});
28+
workbox.routing.registerRoute(API, apiHandler);
29+
30+
// work-images-cache
31+
workbox.routing.registerRoute(/\.(?:jpg|png|json|ico|jpeg|svg)$/,
32+
new workbox.strategies.StaleWhileRevalidate({
33+
cacheName: 'work-images-cache',
34+
plugins: [
35+
new workbox.expiration.ExpirationPlugin({maxEntries: 60}),
36+
new workbox.cacheableResponse.CacheableResponsePlugin({statuses: [0, 200]}),
37+
],
38+
})
39+
);

0 commit comments

Comments
 (0)