├── .babelrc ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── config-overrides.js ├── jsconfig.json ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json ├── server ├── app.js └── index.js └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg └── serviceWorker.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "env", 4 | "react" 5 | ], 6 | "plugins": [ 7 | "transform-decorators-legacy", 8 | "transform-runtime", 9 | "react-hot-loader/babel", 10 | "add-module-exports", 11 | "transform-object-rest-spread", 12 | "transform-class-properties", 13 | [ 14 | "import", 15 | { 16 | "libraryName": "antd", 17 | "style": true 18 | } 19 | ] 20 | ] 21 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babylon", 3 | "printWidth": 120, 4 | "semi": true, 5 | "singleQuote": true, 6 | "jsxBracketSameLine": false 7 | } 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 mantou 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 使用说明 2 | 3 | 该案例是react服务器渲染案例,简称 React SSR,采用create-react-app构建项目。 4 | 5 | 1. **npm install** 安装依赖 6 | 7 | 2. **npm run build** 打包项目 8 | 9 | 3. **npm run server** 启动服务器,访问地址 *http://localhost:3030* 访问项目 10 | 11 | # 前言 12 | 13 | 本文是基于react ssr的入门教程,在实际项目中使用还需要做更多的配置和优化,比较适合第一次尝试react ssr的小伙伴们。技术涉及到 koa2 + react,案例使用create-react-app创建 14 | 15 | # SSR 介绍 16 | Server Slide Rendering,缩写为 **ssr** 即服务器端渲染,这个要从SEO说起,目前react单页应用HTML代码是下面这样的 17 | ```html 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | React App 26 | 27 | 28 | 29 |
30 | 31 | 32 | 33 | ``` 34 | 1. 如果main.js 加载比较慢,会出现白屏一闪的现象。 35 | 2. 传统的搜索引擎爬虫因为不能抓取JS生成后的内容,遇到单页web项目,抓取到的内容啥也没有。在SEO上会吃很多亏,很难排搜索引擎到前面去。 36 | React SSR(react服务器渲染)正好解决了这2个问题。 37 | 38 | # React SSR介绍 39 | 40 | 这里通过一个例子来带大家入坑!先使用create-react-app创建一个react项目。因为要修改webpack,这里我们使用react-app-rewired启动项目。根目录创建一个server目录存放服务端代码,服务端代码我们这里使用koa2。目录结构如下: 41 | 42 | ![图片描述][1] 43 | 44 | 这里先来看看react ssr是怎么工作的。 45 | 46 | ![图片描述][2] 47 | 48 | 这个业务流程图比较清晰了,服务端只生成HTML代码,实际上前端会生成一份main.js提供给服务端的HTML使用。这就是react ssr的工作流程。有了这个图会更好的理解,如果这个业务没理解清楚,后面的估计很难理解。 49 | 50 | > react提供的SSR方法有两个renderToString 和 renderToStaticMarkup,区别如下: 51 | 52 | - renderToString 方法渲染的时候带有 data-reactid 属性. 在浏览器访问页面的时候,main.js能识别到HTML的内容,不会执行React.createElement二次创建DOM。 53 | - renderToStaticMarkup 则没有 data-reactid 属性,页面看上去干净点。在浏览器访问页面的时候,main.js不能识别到HTML内容,会执行main.js里面的React.createElement方法重新创建DOM。 54 | 55 | # 实现流程 56 | 57 | 好了,我们都知道原理了,可以开始coding了,目录结构如下: 58 | 59 | ![图片描述][3] 60 | 61 | create-react-app 的demo我没动过,直接用这个做案例了,前端项目基本上就没改了,等会儿我们服务器端要使用这个模块。代码如下: 62 | 63 | ```javascript 64 | import "./App.css"; 65 | 66 | import React, { Component } from "react"; 67 | 68 | import logo from "./logo.svg"; 69 | 70 | class App extends Component { 71 | componentDidMount() { 72 | console.log('哈哈哈~ 服务器渲染成功了!'); 73 | } 74 | 75 | render() { 76 | return ( 77 |
78 |
79 | logo 80 |

81 | Edit src/App.js and save to reload. 82 |

83 | 89 | Learn React 90 | 91 |
92 |
93 | ); 94 | } 95 | } 96 | 97 | export default App; 98 | 99 | ``` 100 | 101 | 在项目中新建server目录,用于存放服务端代码。为了简化,我这里只有2个文件,项目中我们用的ES6,所以还要配置下.babelrc 102 | 103 | ![图片描述][4] 104 | 105 | > .babelrc 配置,因为要使用到ES6 106 | ```json 107 | { 108 | "presets": [ 109 | "env", 110 | "react" 111 | ], 112 | "plugins": [ 113 | "transform-decorators-legacy", 114 | "transform-runtime", 115 | "react-hot-loader/babel", 116 | "add-module-exports", 117 | "transform-object-rest-spread", 118 | "transform-class-properties", 119 | [ 120 | "import", 121 | { 122 | "libraryName": "antd", 123 | "style": true 124 | } 125 | ] 126 | ] 127 | } 128 | ``` 129 | 130 | > index.js 项目入口做一些预处理,使用asset-require-hook过滤掉一些类似 ```import logo from "./logo.svg";``` 这样的资源代码。因为我们服务端只需要纯的HTML代码,不过滤掉会报错。这里的name,我们是去掉了hash值的 131 | 132 | ```javascript 133 | require("asset-require-hook")({ 134 | extensions: ["svg", "css", "less", "jpg", "png", "gif"], 135 | name: '/static/media/[name].[ext]' 136 | }); 137 | require("babel-core/register")(); 138 | require("babel-polyfill"); 139 | require("./app"); 140 | ``` 141 | 142 | > public/index.html html模版代码要做个调整,```{{root}}``` 这个可以是任何可以替换的字符串,等下服务端会替换这段字符串。 143 | 144 | ```html 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | React App 154 | 155 | 156 | 157 |
{{root}}
158 | 159 | 160 | 161 | ``` 162 | 163 | > app.js 服务端渲染的主要代码,加载App.js,使用renderToString 生成html代码,去替换掉 index.html 中的 ```{{root}}``` 部分 164 | 165 | ```javascript 166 | import App from '../src/App'; 167 | import Koa from 'koa'; 168 | import React from 'react'; 169 | import Router from 'koa-router'; 170 | import fs from 'fs'; 171 | import koaStatic from 'koa-static'; 172 | import path from 'path'; 173 | import { renderToString } from 'react-dom/server'; 174 | 175 | // 配置文件 176 | const config = { 177 | port: 3030 178 | }; 179 | 180 | // 实例化 koa 181 | const app = new Koa(); 182 | 183 | // 静态资源 184 | app.use( 185 | koaStatic(path.join(__dirname, '../build'), { 186 | maxage: 365 * 24 * 60 * 1000, 187 | index: 'root' 188 | // 这里配置不要写成'index'就可以了,因为在访问localhost:3030时,不能让服务默认去加载index.html文件,这里很容易掉进坑。 189 | }) 190 | ); 191 | 192 | // 设置路由 193 | app.use( 194 | new Router() 195 | .get('*', async (ctx, next) => { 196 | ctx.response.type = 'html'; //指定content type 197 | let shtml = ''; 198 | await new Promise((resolve, reject) => { 199 | fs.readFile(path.join(__dirname, '../build/index.html'), 'utfa8', function(err, data) { 200 | if (err) { 201 | reject(); 202 | return console.log(err); 203 | } 204 | shtml = data; 205 | resolve(); 206 | }); 207 | }); 208 | // 替换掉 {{root}} 为我们生成后的HTML 209 | ctx.response.body = shtml.replace('{{root}}', renderToString()); 210 | }) 211 | .routes() 212 | ); 213 | 214 | app.listen(config.port, function() { 215 | console.log('服务器启动,监听 port: ' + config.port + ' running~'); 216 | }); 217 | 218 | ``` 219 | 220 | > config-overrides.js 因为我们用的是create-react-app,这里使用react-app-rewired去改下webpack的配置。因为执行**npm run build**的时候会自动给资源加了hash值,而这个hash值,我们在asset-require-hook的时候去掉了hash值,配置里面需要改下,不然会出现图片不显示的问题,这里也是一个坑,要注意下。 221 | 222 | ```javascript 223 | module.exports = { 224 | webpack: function(config, env) { 225 | // ...add your webpack config 226 | // console.log(JSON.stringify(config)); 227 | // 去掉hash值,解决asset-require-hook资源问题 228 | config.module.rules.forEach(d => { 229 | d.oneOf && 230 | d.oneOf.forEach(e => { 231 | if (e && e.options && e.options.name) { 232 | e.options.name = e.options.name.replace('[hash:8].', ''); 233 | } 234 | }); 235 | }); 236 | return config; 237 | } 238 | }; 239 | 240 | ``` 241 | 242 | 好了,所有的代码就这些了,是不是很简单了?我们koa2读取的静态资源是 build目录下面的。先执行**npm run build**打包项目,再执行**node ./server** 启动服务端项目。看下http://localhost:3030页面的HTML代码检查下: 243 | 244 | ![图片描述][5] 245 | 246 | ![图片描述][6] 247 | 248 | 没有```{{root}}```了,服务器渲染成功! 249 | 250 | # 总结 251 | 252 | 相信这篇文章是最简单的react服务器渲染案例了,这里交出github地址,如果学会了,记得给个star 253 | 254 | > https://github.com/mtsee/react-koa2-ssr 255 | 256 | 257 | [1]: https://image-static.segmentfault.com/172/820/1728206619-5c765504b90de_articlex 258 | [2]: https://image-static.segmentfault.com/147/717/1477175201-5c7657d0d7a29_articlex 259 | [3]: https://image-static.segmentfault.com/337/614/3376146941-5c76632940970_articlex 260 | [4]: https://image-static.segmentfault.com/114/696/1146964533-5c765ba08f00b_articlex 261 | [5]: https://image-static.segmentfault.com/117/321/1173215685-5c76616aa0cd0_articlex 262 | [6]: https://image-static.segmentfault.com/714/996/714996020-5c7661032ad25_articlex -------------------------------------------------------------------------------- /config-overrides.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | webpack: function(config, env) { 3 | // ...add your webpack config 4 | // console.log(JSON.stringify(config)); 5 | // 去掉hash值,解决asset-require-hook资源问题 6 | config.module.rules.forEach(d => { 7 | d.oneOf && 8 | d.oneOf.forEach(e => { 9 | if (e && e.options && e.options.name) { 10 | e.options.name = e.options.name.replace('[hash:8].', ''); 11 | } 12 | }); 13 | }); 14 | return config; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "experimentalDecorators": true 4 | } 5 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-koa2-ssr-mantou", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "antd": "^3.13.6", 7 | "asset-require-hook": "^1.2.0", 8 | "koa": "^2.7.0", 9 | "koa-body": "^4.0.8", 10 | "koa-cors": "^0.0.16", 11 | "koa-helmet": "^4.0.0", 12 | "koa-logger": "^3.2.0", 13 | "koa-response-time": "^2.1.0", 14 | "koa-router": "^7.4.0", 15 | "koa-session": "^5.10.1", 16 | "koa-static": "^5.0.0", 17 | "koa-views": "^6.1.5", 18 | "react": "^16.8.3", 19 | "react-dom": "^16.8.3", 20 | "react-scripts": "2.1.5" 21 | }, 22 | "scripts": { 23 | "eject": "react-scripts eject", 24 | "start": "react-app-rewired start", 25 | "build": "react-app-rewired build", 26 | "test": "react-app-rewired test --env=jsdom", 27 | "server": "node ./server" 28 | }, 29 | "eslintConfig": { 30 | "extends": "react-app" 31 | }, 32 | "browserslist": [ 33 | ">0.2%", 34 | "not dead", 35 | "not ie <= 11", 36 | "not op_mini all" 37 | ], 38 | "devDependencies": { 39 | "babel-cli": "^6.26.0", 40 | "babel-core": "^6.26.3", 41 | "babel-eslint": "9.0.0", 42 | "babel-loader": "^8.0.5", 43 | "babel-plugin-add-module-exports": "^1.0.0", 44 | "babel-plugin-import": "^1.11.0", 45 | "babel-plugin-transform-class-properties": "^6.24.1", 46 | "babel-plugin-transform-decorators": "^6.24.1", 47 | "babel-plugin-transform-decorators-legacy": "^1.3.5", 48 | "babel-plugin-transform-object-rest-spread": "^6.26.0", 49 | "babel-plugin-transform-runtime": "^6.23.0", 50 | "babel-polyfill": "^6.26.0", 51 | "babel-preset-env": "^1.7.0", 52 | "babel-preset-react": "^6.24.1", 53 | "react-app-rewire-less": "^2.1.3", 54 | "react-app-rewired": "^2.1.0", 55 | "react-hot-loader": "^4.7.1" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mtsee/react-koa2-ssr/6e7d782a0397d148d82c8900de12056ab8dd29d9/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 25 | React App 26 | 27 | 28 | 29 |
{{root}}
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /server/app.js: -------------------------------------------------------------------------------- 1 | import App from '../src/App'; 2 | import Koa from 'koa'; 3 | import React from 'react'; 4 | import Router from 'koa-router'; 5 | import fs from 'fs'; 6 | import koaStatic from 'koa-static'; 7 | import path from 'path'; 8 | import { renderToString } from 'react-dom/server'; 9 | 10 | // 配置文件 11 | const config = { 12 | port: 3030 13 | }; 14 | 15 | // 实例化 koa 16 | const app = new Koa(); 17 | 18 | // 静态资源 19 | app.use( 20 | koaStatic(path.join(__dirname, '../build'), { 21 | maxage: 365 * 24 * 60 * 1000, 22 | index: 'root' 23 | // 这里配置不要写成'index'就可以了,因为在访问localhost:3030时,不能让服务默认去加载index.html文件,这里很容易掉进坑。 24 | }) 25 | ); 26 | 27 | // 设置路由 28 | app.use( 29 | new Router() 30 | .get('*', async (ctx, next) => { 31 | ctx.response.type = 'html'; //指定content type 32 | let shtml = ''; 33 | await new Promise((resolve, reject) => { 34 | fs.readFile(path.join(__dirname, '../build/index.html'), 'utfa8', function(err, data) { 35 | if (err) { 36 | reject(); 37 | return console.log(err); 38 | } 39 | shtml = data; 40 | resolve(); 41 | }); 42 | }); 43 | // 替换掉 {{root}} 为我们生成后的HTML 44 | ctx.response.body = shtml.replace('{{root}}', renderToString()); 45 | }) 46 | .routes() 47 | ); 48 | 49 | app.listen(config.port, function() { 50 | console.log('服务器启动,监听 port: ' + config.port + ' running~'); 51 | }); 52 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | require("asset-require-hook")({ 2 | extensions: ["svg", "css", "less", "jpg", "png", "gif"], 3 | name: '/static/media/[name].[ext]' 4 | }); 5 | require("babel-core/register")(); 6 | require("babel-polyfill"); 7 | require("./app"); 8 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 40vmin; 8 | pointer-events: none; 9 | } 10 | 11 | .App-header { 12 | background-color: #282c34; 13 | min-height: 100vh; 14 | display: flex; 15 | flex-direction: column; 16 | align-items: center; 17 | justify-content: center; 18 | font-size: calc(10px + 2vmin); 19 | color: white; 20 | } 21 | 22 | .App-link { 23 | color: #61dafb; 24 | } 25 | 26 | @keyframes App-logo-spin { 27 | from { 28 | transform: rotate(0deg); 29 | } 30 | to { 31 | transform: rotate(360deg); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import "./App.css"; 2 | 3 | import React, { Component } from "react"; 4 | 5 | import logo from "./logo.svg"; 6 | 7 | class App extends Component { 8 | componentDidMount() { 9 | console.log('哈哈哈~ 服务器渲染成功了!'); 10 | } 11 | 12 | render() { 13 | return ( 14 |
15 |
16 | logo 17 |

18 | Edit src/App.js and save to reload. 19 |

20 | 26 | Learn React 27 | 28 |
29 |
30 | ); 31 | } 32 | } 33 | 34 | export default App; 35 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: http://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read http://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------