Skip to content

Commit d4737bd

Browse files
committed
feat($build): Added the support for PWA
Added SWPrecacheWebpackPlugin and a service worker to serve assets from local cache
1 parent 895f0b3 commit d4737bd

File tree

7 files changed

+460
-13
lines changed

7 files changed

+460
-13
lines changed

config/webpack.config.prod.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
const autoprefixer = require('autoprefixer');
4+
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
45
const DefinePlugin = require('webpack/lib/DefinePlugin');
56
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
67
const HtmlWebpackPlugin = require('html-webpack-plugin');
@@ -195,6 +196,37 @@ module.exports = {
195196
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
196197
new ExtractTextPlugin({
197198
filename: cssFilename
198-
})
199+
}),
200+
201+
// Generate a service worker script that will precache, and keep up to date,
202+
// the HTML & assets that are part of the Webpack build.
203+
new SWPrecacheWebpackPlugin({
204+
// By default, a cache-busting query parameter is appended to requests
205+
// used to populate the caches, to ensure the responses are fresh.
206+
// If a URL is already hashed by Webpack, then there is no concern
207+
// about it being stale, and the cache-busting can be skipped.
208+
dontCacheBustUrlsMatching: /\.\w{8}\./,
209+
filename: 'service-worker.js',
210+
logger(message) {
211+
if (message.indexOf('Total precache size is') === 0) {
212+
// This message occurs for every build and is a bit too noisy.
213+
return;
214+
}
215+
if (message.indexOf('Skipping static resource') === 0) {
216+
// This message obscures real errors so we ignore it.
217+
// https://github.com/facebookincubator/create-react-app/issues/2612
218+
return;
219+
}
220+
console.log(message);
221+
},
222+
minify: true,
223+
// For unknown URLs, fallback to the index page
224+
navigateFallback: publicUrl + '/index.html',
225+
// Ignores URLs starting from /__ (useful for Firebase):
226+
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
227+
navigateFallbackWhitelist: [/^(?!\/__).*/],
228+
// Don't precache sourcemaps (they're large) and build asset manifest:
229+
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
230+
}),
199231
]
200232
};

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"react-error-overlay": "^1.0.10",
4949
"string-replace-loader": "^1.3.0",
5050
"style-loader": "^0.18.1",
51+
"sw-precache-webpack-plugin": "^0.11.4",
5152
"url-loader": "^0.5.9",
5253
"webpack": "^3.5.5",
5354
"webpack-dev-server": "^2.7.1"

template/public/index.html

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44
<meta charset="utf-8">
55
<meta http-equiv="x-ua-compatible" content="ie=edge">
66
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
7+
<meta name="theme-color" content="#000000">
8+
<!--
9+
manifest.json provides metadata used when your web app is added to the
10+
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
11+
-->
12+
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
713
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
814
<title>Elm App</title>
915
</head>

template/public/manifest.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"short_name": "Elm App",
3+
"name": "Create Elm App Sample",
4+
"icons": [
5+
{
6+
"src": "favicon.ico",
7+
"sizes": "192x192",
8+
"type": "image/png"
9+
}
10+
],
11+
"start_url": "./index.html",
12+
"display": "standalone",
13+
"theme_color": "#000000",
14+
"background_color": "#ffffff"
15+
}

template/src/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
import './main.css';
22
import { Main } from './Main.elm';
3+
import registerServiceWorker from './registerServiceWorker';
34

45
Main.embed(document.getElementById('root'));
6+
7+
registerServiceWorker();
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// In production, we register a service worker to serve assets from local cache.
2+
3+
// This lets the app load faster on subsequent visits in production, and gives
4+
// it offline capabilities. However, it also means that developers (and users)
5+
// will only see deployed updates on the "N+1" visit to a page, since previously
6+
// cached resources are updated in the background.
7+
8+
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
9+
// This link also includes instructions on opting out of this behavior.
10+
11+
const isLocalhost = Boolean(
12+
window.location.hostname === 'localhost' ||
13+
// [::1] is the IPv6 localhost address.
14+
window.location.hostname === '[::1]' ||
15+
// 127.0.0.1/8 is considered localhost for IPv4.
16+
window.location.hostname.match(
17+
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
18+
)
19+
);
20+
21+
export default function register() {
22+
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
23+
// The URL constructor is available in all browsers that support SW.
24+
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
25+
if (publicUrl.origin !== window.location.origin) {
26+
// Our service worker won't work if PUBLIC_URL is on a different origin
27+
// from what our page is served on. This might happen if a CDN is used to
28+
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
29+
return;
30+
}
31+
32+
window.addEventListener('load', () => {
33+
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
34+
35+
if (!isLocalhost) {
36+
// Is not local host. Just register service worker
37+
registerValidSW(swUrl);
38+
} else {
39+
// This is running on localhost. Lets check if a service worker still exists or not.
40+
checkValidServiceWorker(swUrl);
41+
}
42+
});
43+
}
44+
}
45+
46+
function registerValidSW(swUrl) {
47+
navigator.serviceWorker
48+
.register(swUrl)
49+
.then(registration => {
50+
registration.onupdatefound = () => {
51+
const installingWorker = registration.installing;
52+
installingWorker.onstatechange = () => {
53+
if (installingWorker.state === 'installed') {
54+
if (navigator.serviceWorker.controller) {
55+
// At this point, the old content will have been purged and
56+
// the fresh content will have been added to the cache.
57+
// It's the perfect time to display a "New content is
58+
// available; please refresh." message in your web app.
59+
console.log('New content is available; please refresh.');
60+
} else {
61+
// At this point, everything has been precached.
62+
// It's the perfect time to display a
63+
// "Content is cached for offline use." message.
64+
console.log('Content is cached for offline use.');
65+
}
66+
}
67+
};
68+
};
69+
})
70+
.catch(error => {
71+
console.error('Error during service worker registration:', error);
72+
});
73+
}
74+
75+
function checkValidServiceWorker(swUrl) {
76+
// Check if the service worker can be found. If it can't reload the page.
77+
fetch(swUrl)
78+
.then(response => {
79+
// Ensure service worker exists, and that we really are getting a JS file.
80+
if (
81+
response.status === 404 ||
82+
response.headers.get('content-type').indexOf('javascript') === -1
83+
) {
84+
// No service worker found. Probably a different app. Reload the page.
85+
navigator.serviceWorker.ready.then(registration => {
86+
registration.unregister().then(() => {
87+
window.location.reload();
88+
});
89+
});
90+
} else {
91+
// Service worker found. Proceed as normal.
92+
registerValidSW(swUrl);
93+
}
94+
})
95+
.catch(() => {
96+
console.log(
97+
'No internet connection found. App is running in offline mode.'
98+
);
99+
});
100+
}
101+
102+
export function unregister() {
103+
if ('serviceWorker' in navigator) {
104+
navigator.serviceWorker.ready.then(registration => {
105+
registration.unregister();
106+
});
107+
}
108+
}

0 commit comments

Comments
 (0)