From b2ce2cad210412d3ac1aa445beaeee132b3659a0 Mon Sep 17 00:00:00 2001 From: Gyandeep Singh Date: Sun, 3 Sep 2017 20:44:43 -0500 Subject: [PATCH] New: Add offline support using service workers (fixes #23) --- .npmrc | 1 + next.config.js | 23 ++++++++++++++++++++++- package.json | 3 ++- pages/index.js | 13 +++++++++++++ 4 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 .npmrc diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..43c97e7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +package-lock=false diff --git a/next.config.js b/next.config.js index 7bd4c6f..722a75a 100644 --- a/next.config.js +++ b/next.config.js @@ -3,6 +3,7 @@ const webpack = require("webpack") const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') const { ANALYZE } = process.env const glob = require("glob") +const SWPrecacheWebpackPlugin = require("sw-precache-webpack-plugin") module.exports = { webpack: (config, { dev }) => { @@ -27,6 +28,26 @@ module.exports = { config.plugins.push( new BabiliPlugin() ) + + config.plugins.push( + new SWPrecacheWebpackPlugin({ + minify: true, + staticFileGlobsIgnorePatterns: [/\.next\//], + staticFileGlobs: [ + 'static/**/*' // Precache all static files by default + ], + runtimeCaching: [ + { + handler: 'fastest', + urlPattern: /[.](png|jpg|css)/ + }, + { + handler: "networkFirst", + urlPattern: /^https?.*/ + } + ] + }) + ) } if (ANALYZE) { @@ -49,4 +70,4 @@ module.exports = { }) return pathMap } -}; \ No newline at end of file +}; diff --git a/package.json b/package.json index 43d085e..b183dae 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "main": "index.js", "scripts": { "start": "next start", - "build": "rm -rf out && next build && next export", + "build": "rm -rf out && next build && next export && cp ./.next/service-worker.js ./out/service-worker.js", "dev": "next dev", "addContributor": "all-contributors add", "analyze": "cross-env ANALYZE=1 next build", @@ -51,6 +51,7 @@ "glob": "^7.1.2", "prettier": "^1.6.1", "style-loader": "^0.18.2", + "sw-precache-webpack-plugin": "^0.11.4", "webpack-bundle-analyzer": "^2.9.0" } } diff --git a/pages/index.js b/pages/index.js index 03dcc80..6f0f984 100644 --- a/pages/index.js +++ b/pages/index.js @@ -30,6 +30,19 @@ export default class Main extends PureComponent { ${code}`; }; + async componentDidMount() { + if ("serviceWorker" in navigator) { + navigator.serviceWorker + .register("/service-worker.js") + .then(registration => { + console.log("service worker registration successful"); + }) + .catch(err => { + console.warn("service worker registration failed"); + }); + } + } + render() { return (