├── public ├── favicon.ico ├── logo192.png ├── logo512.png ├── robots.txt ├── manifest.json └── index.html ├── src ├── reducers │ ├── index.js │ ├── visibilityFilter.js │ └── todos.js ├── setupTests.js ├── App.test.js ├── components │ ├── Header.js │ ├── Home.js │ ├── Todo.js │ ├── Link.js │ ├── Footer.js │ ├── TodoList.js │ └── Page.js ├── configure-store.js ├── index.css ├── actions │ └── index.js ├── containers │ ├── FilterLink.js │ ├── AddTodo.js │ └── VisibleTodoList.js ├── index.js ├── App.css ├── App.js ├── logo.svg └── serviceWorker.js ├── .gitignore ├── server ├── bootstrap.js ├── index.js └── react-renderer.js ├── package.json └── README.md /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dariomac/poc-cra-ssr/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dariomac/poc-cra-ssr/HEAD/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dariomac/poc-cra-ssr/HEAD/public/logo512.png -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/reducers/index.js: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import todos from './todos'; 3 | import visibilityFilter from './visibilityFilter'; 4 | 5 | export default combineReducers({ 6 | todos, 7 | visibilityFilter 8 | }) 9 | -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /src/components/Header.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import logo from '../logo.svg'; 3 | 4 | const Header = () => ( 5 |
6 | logo 7 | 8 |

9 | CRA + SSR 10 |

11 |
12 | ); 13 | 14 | export default Header; 15 | -------------------------------------------------------------------------------- /src/reducers/visibilityFilter.js: -------------------------------------------------------------------------------- 1 | import { VisibilityFilters } from '../actions' 2 | const visibilityFilter = (state = VisibilityFilters.SHOW_ALL, action) => { 3 | switch (action.type) { 4 | case 'SET_VISIBILITY_FILTER': 5 | return action.filter 6 | default: 7 | return state 8 | } 9 | } 10 | export default visibilityFilter 11 | -------------------------------------------------------------------------------- /src/configure-store.js: -------------------------------------------------------------------------------- 1 | import { createStore } from "redux"; 2 | import rootReducer from "./reducers"; 3 | 4 | const enhancer = global.window && global.window.__REDUX_DEVTOOLS_EXTENSION__ && global.window.__REDUX_DEVTOOLS_EXTENSION__(); 5 | 6 | export default function configureStore(preloadedState = {}) { 7 | return createStore( 8 | rootReducer, 9 | preloadedState, 10 | enhancer 11 | ) 12 | }; 13 | -------------------------------------------------------------------------------- /src/components/Home.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Footer from './Footer'; 3 | import Header from './Header'; 4 | import AddTodo from '../containers/AddTodo'; 5 | import VisibleTodoList from '../containers/VisibleTodoList'; 6 | 7 | const Home = () => ( 8 |
9 |
10 | 11 | 12 |
13 |
14 | ); 15 | 16 | export default Home; 17 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/actions/index.js: -------------------------------------------------------------------------------- 1 | export const addTodo = text => ({ 2 | type: 'ADD_TODO', 3 | text 4 | }) 5 | export const setVisibilityFilter = filter => ({ 6 | type: 'SET_VISIBILITY_FILTER', 7 | filter 8 | }) 9 | export const toggleTodo = id => ({ 10 | type: 'TOGGLE_TODO', 11 | id 12 | }) 13 | export const VisibilityFilters = { 14 | SHOW_ALL: 'SHOW_ALL', 15 | SHOW_COMPLETED: 'SHOW_COMPLETED', 16 | SHOW_ACTIVE: 'SHOW_ACTIVE' 17 | } 18 | -------------------------------------------------------------------------------- /src/components/Todo.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import PropTypes from 'prop-types' 3 | const Todo = ({ onClick, completed, text }) => ( 4 |
  • 10 | {text} 11 |
  • 12 | ) 13 | Todo.propTypes = { 14 | onClick: PropTypes.func.isRequired, 15 | completed: PropTypes.bool.isRequired, 16 | text: PropTypes.string.isRequired 17 | } 18 | export default Todo 19 | -------------------------------------------------------------------------------- /src/components/Link.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import PropTypes from 'prop-types' 3 | const Link = ({ active, children, onClick }) => ( 4 | 13 | ) 14 | Link.propTypes = { 15 | active: PropTypes.bool.isRequired, 16 | children: PropTypes.node.isRequired, 17 | onClick: PropTypes.func.isRequired 18 | } 19 | export default Link 20 | -------------------------------------------------------------------------------- /src/containers/FilterLink.js: -------------------------------------------------------------------------------- 1 | import { connect } from 'react-redux' 2 | import { setVisibilityFilter } from '../actions' 3 | import Link from '../components/Link' 4 | const mapStateToProps = (state, ownProps) => ({ 5 | active: ownProps.filter === state.visibilityFilter 6 | }) 7 | const mapDispatchToProps = (dispatch, ownProps) => ({ 8 | onClick: () => dispatch(setVisibilityFilter(ownProps.filter)) 9 | }) 10 | export default connect( 11 | mapStateToProps, 12 | mapDispatchToProps 13 | )(Link) 14 | -------------------------------------------------------------------------------- /server/bootstrap.js: -------------------------------------------------------------------------------- 1 | require('ignore-styles'); 2 | 3 | require('@babel/register')({ 4 | "presets": [ 5 | "@babel/preset-env", 6 | "@babel/preset-react" 7 | ], 8 | "plugins": [ 9 | //"@babel/plugin-transform-modules-commonjs", 10 | [ 11 | "transform-assets", 12 | { 13 | "extensions": [ 14 | "css", 15 | "svg" 16 | ], 17 | "name": "static/media/[name].[hash:8].[ext]" 18 | } 19 | ] 20 | ] 21 | }); 22 | 23 | require('./index'); 24 | -------------------------------------------------------------------------------- /src/reducers/todos.js: -------------------------------------------------------------------------------- 1 | const todos = (state = [], action) => { 2 | switch (action.type) { 3 | case 'ADD_TODO': 4 | const nextTaskId = state ? state.length : 0; 5 | 6 | return [ 7 | ...state, 8 | { 9 | id: nextTaskId, 10 | text: action.text, 11 | completed: false 12 | } 13 | ]; 14 | case 'TOGGLE_TODO': 15 | return state.map(todo => 16 | todo.id === action.id ? { ...todo, completed: !todo.completed } : todo 17 | ); 18 | default: 19 | return state; 20 | } 21 | }; 22 | export default todos; 23 | -------------------------------------------------------------------------------- /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 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /src/components/Footer.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import FilterLink from '../containers/FilterLink' 3 | import { VisibilityFilters } from '../actions' 4 | import { Link } from "react-router-dom"; 5 | 6 | const Footer = () => ( 7 |
    8 | Show: 9 | All 10 | Active 11 | Completed 12 | Test page (link through client router)! 13 |
    14 | ) 15 | export default Footer 16 | -------------------------------------------------------------------------------- /src/components/TodoList.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import PropTypes from 'prop-types' 3 | import Todo from './Todo' 4 | const TodoList = ({ todos, toggleTodo }) => ( 5 | 10 | ) 11 | TodoList.propTypes = { 12 | todos: PropTypes.arrayOf( 13 | PropTypes.shape({ 14 | id: PropTypes.number.isRequired, 15 | completed: PropTypes.bool.isRequired, 16 | text: PropTypes.string.isRequired 17 | }).isRequired 18 | ).isRequired, 19 | toggleTodo: PropTypes.func.isRequired 20 | } 21 | export default TodoList 22 | -------------------------------------------------------------------------------- /src/containers/AddTodo.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { connect } from 'react-redux' 3 | import { addTodo } from '../actions' 4 | const AddTodo = ({ dispatch }) => { 5 | let input 6 | return ( 7 |
    8 |
    { 10 | e.preventDefault() 11 | if (!input.value.trim()) { 12 | return 13 | } 14 | dispatch(addTodo(input.value)) 15 | input.value = '' 16 | }} 17 | > 18 | (input = node)} /> 19 | 20 |
    21 |
    22 | ) 23 | } 24 | export default connect()(AddTodo) 25 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom'; 3 | 4 | import App from './App' 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | import configureStore from './configure-store'; 8 | 9 | const initialState = global.window && global.window.__INITIAL_STATE__ 10 | const store = configureStore(initialState); 11 | 12 | ReactDOM.hydrate(, document.getElementById('root')); 13 | 14 | // If you want your app to work offline and load faster, you can change 15 | // unregister() to register() below. Note this comes with some pitfalls. 16 | // Learn more about service workers: https://bit.ly/CRA-PWA 17 | serviceWorker.unregister(); 18 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 40vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | margin-bottom: 2vmin; 26 | } 27 | 28 | .App-header p { 29 | margin: 1.5vmin; 30 | } 31 | 32 | .App-link { 33 | color: #61dafb; 34 | } 35 | 36 | @keyframes App-logo-spin { 37 | from { 38 | transform: rotate(0deg); 39 | } 40 | to { 41 | transform: rotate(360deg); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/components/Page.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { connect } from 'react-redux' 3 | import { Link } from "react-router-dom"; 4 | 5 | const Page = ({ todos }) => { 6 | /** 7 | * You can't useEffect server side because is a no-op 8 | * https://github.com/gatsbyjs/gatsby/issues/13947#issuecomment-491214724 9 | */ 10 | 11 | return ( 12 |
    13 |

    THIS IS A PAGE! ({ todos.length } todos in the state)

    14 |

    { todos[todos.length-1].text }

    15 | Home 16 |
    17 | ); 18 | } 19 | 20 | const mapStateToProps = state => { 21 | return ({ 22 | todos: state.todos 23 | }); 24 | } 25 | 26 | const mapDispatchToProps = dispatch => ({ 27 | 28 | }); 29 | 30 | export default connect( 31 | mapStateToProps, 32 | mapDispatchToProps 33 | )(Page); 34 | -------------------------------------------------------------------------------- /src/containers/VisibleTodoList.js: -------------------------------------------------------------------------------- 1 | import { connect } from 'react-redux' 2 | import { toggleTodo } from '../actions' 3 | import TodoList from '../components/TodoList' 4 | import { VisibilityFilters } from '../actions' 5 | const getVisibleTodos = (todos, filter) => { 6 | switch (filter) { 7 | case VisibilityFilters.SHOW_ALL: 8 | return todos 9 | case VisibilityFilters.SHOW_COMPLETED: 10 | return todos.filter(t => t.completed) 11 | case VisibilityFilters.SHOW_ACTIVE: 12 | return todos.filter(t => !t.completed) 13 | default: 14 | throw new Error('Unknown filter: ' + filter) 15 | } 16 | } 17 | const mapStateToProps = state => ({ 18 | todos: getVisibleTodos(state.todos, state.visibilityFilter) 19 | }) 20 | const mapDispatchToProps = dispatch => ({ 21 | toggleTodo: id => dispatch(toggleTodo(id)) 22 | }) 23 | export default connect( 24 | mapStateToProps, 25 | mapDispatchToProps 26 | )(TodoList) 27 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const path = require('path'); 3 | 4 | const PORT = 3000; 5 | 6 | const reactRenderer = require('./react-renderer'); 7 | const routes = ['/', '/page']; 8 | 9 | /** 10 | * initialize the application and create the routes 11 | */ 12 | const app = express(); 13 | 14 | /** 15 | * "/path-in-out-routes-arr" should always serve our server rendered page; 16 | * otherwise, continue with next handlers 17 | */ 18 | app.get('/*', reactRenderer.render(routes)); 19 | 20 | /** 21 | * Set the location of the static assets (ie the js bundle generated by webapck) 22 | */ 23 | app.use(express.static(path.resolve(__dirname, '../build'))) 24 | app.use(express.static(path.resolve(__dirname, '../public'))) 25 | 26 | /** 27 | * Since this is the last non-error-handling 28 | * middleware use()d, we assume 404, as nothing else 29 | * responded. 30 | */ 31 | app.use(reactRenderer.render(routes)); 32 | 33 | app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`)); 34 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@babel/core": "^7.7.7", 7 | "@babel/preset-env": "^7.7.7", 8 | "@babel/preset-react": "^7.7.4", 9 | "@babel/register": "^7.7.7", 10 | "@testing-library/jest-dom": "^4.2.4", 11 | "@testing-library/react": "^9.3.2", 12 | "@testing-library/user-event": "^7.1.2", 13 | "babel-plugin-transform-assets": "^1.0.2", 14 | "express": "^4.17.1", 15 | "ignore-styles": "^5.0.1", 16 | "react": "^16.13.1", 17 | "react-dom": "^16.13.1", 18 | "react-redux": "^7.1.3", 19 | "react-router": "^5.1.2", 20 | "react-router-dom": "^5.1.2", 21 | "react-scripts": "3.4.1", 22 | "redux": "^4.0.5" 23 | }, 24 | "scripts": { 25 | "start": "react-scripts start", 26 | "build": "react-scripts build", 27 | "test": "react-scripts test", 28 | "eject": "react-scripts eject", 29 | "start-server": "yarn build && NODE_ENV=production node server/bootstrap.js" 30 | }, 31 | "eslintConfig": { 32 | "extends": "react-app" 33 | }, 34 | "browserslist": { 35 | "production": [ 36 | ">0.2%", 37 | "not dead", 38 | "not op_mini all" 39 | ], 40 | "development": [ 41 | "last 1 chrome version", 42 | "last 1 firefox version", 43 | "last 1 safari version" 44 | ] 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Provider } from 'react-redux'; 3 | import Home from './components/Home'; 4 | import Page from './components/Page'; 5 | import { Route, Switch, BrowserRouter } from 'react-router-dom'; 6 | import { StaticRouter } from 'react-router'; 7 | import { addTodo } from './actions'; 8 | 9 | import './App.css'; 10 | 11 | const NoMatch = () => ( 12 |
    13 |

    404

    14 | React Page Not Found 15 |
    16 | ); 17 | 18 | const AppRoutes = ({ store }) => ( 19 | 20 | 21 | {/* */} 22 | { 23 | if (store) { 24 | // Bad & ugly just to change the store server side through actions before rendering 25 | store.dispatch(addTodo('This should come renderer from server (on /Page direct hit)')); 26 | } 27 | 28 | return ; 29 | }} exact /> 30 | 31 | 32 | ) 33 | 34 | function App (props) { 35 | return ( 36 | 37 | { 38 | props.location 39 | ? ( 40 | 41 | 42 | 43 | ) : ( 44 | 45 | 46 | 47 | ) 48 | } 49 | 50 | ); 51 | } 52 | export default App; 53 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
    32 | 33 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /server/react-renderer.js: -------------------------------------------------------------------------------- 1 | const React = require('react') 2 | const renderToString = require('react-dom/server').renderToString; 3 | const matchPath = require('react-router').matchPath; 4 | const path = require('path'); 5 | const fs = require('fs'); 6 | const configureStore = require('../src/configure-store').default; 7 | 8 | const initialState = { 9 | todos: [ 10 | { 11 | id: 0, 12 | text: 'Task in initialState from server', 13 | completed: false 14 | }, 15 | ], 16 | }; 17 | 18 | /** 19 | * Import our main App component 20 | * Remember it's exported as ES6 module, so to require it, you must call .default 21 | */ 22 | const App = require('../src/App').default; 23 | 24 | exports = module.exports; 25 | 26 | exports.render = (routes) => { 27 | return (req, res, next) => { 28 | 29 | /** 30 | * Take routes collection and see if it's a valid app's route 31 | */ 32 | var match = routes.find(route => matchPath(req.path, { 33 | path: route, 34 | exact: true, 35 | })); 36 | 37 | const is404 = req._possible404; 38 | 39 | if (match || is404) { 40 | /** 41 | * Point to the html file created by CRA's build tool and open it 42 | */ 43 | const filePath = path.resolve(__dirname, '..', 'build', 'index.html'); 44 | 45 | fs.readFile(filePath, 'utf8', (err, htmlData) => { 46 | if (err) { 47 | console.error('err', err); 48 | return res.status(404).end(); // WARNING: This 404 will be handled by Express server and won't be your React 404 component. 49 | } 50 | 51 | const location = req.url; 52 | 53 | if (is404) { 54 | /** 55 | * Set the app's response to 404 OK (https://httpstatuses.com/404) 56 | */ 57 | res.writeHead(404, { 'Content-Type': 'text/html' }) 58 | console.log(`SSR of unrouted path ${req.path} (404 ahead)`) 59 | } 60 | else { 61 | /** 62 | * Set the app's response to 200 OK (https://httpstatuses.com/200) 63 | */ 64 | res.writeHead(200, { 'Content-Type': 'text/html' }) 65 | console.log(`SSR of ${req.path}`); 66 | } 67 | 68 | const store = configureStore(initialState); 69 | 70 | /** 71 | * Convert JSX code to a HTML string that can be rendered server-side with 72 | * `renderToString` a method provided by ReactDOMServer 73 | * 74 | * This sets up the app so that calling ReactDOM.hydrate() will preserve the 75 | * rendered HTML and only attach event handlers. 76 | * (https://reactjs.org/docs/react-dom-server.html#rendertostring) 77 | */ 78 | const jsx = 79 | const reactDom = renderToString(jsx); 80 | 81 | /** 82 | * inject the rendered app and it state 83 | * into our html and send it 84 | */ 85 | return res.end( 86 | htmlData.replace( 87 | '
    ', 88 | `
    ${reactDom}
    ` 89 | ).replace( 90 | '__REDUX__', 91 | JSON.stringify(store.getState()) 92 | ) 93 | ); 94 | }); 95 | } 96 | else { 97 | req._possible404 = true; 98 | return next(); 99 | } 100 | }; 101 | }; 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## How to run the project 4 | 5 | Before running any script you should run: 6 | 7 | `yarn install` 8 | 9 | Or 10 | 11 | `npm install` 12 | 13 | In the project directory, you can run: 14 | 15 | ### `yarn start-server` or `npm run start-server` 16 | 17 | Runs the app in production mode (although is a PoC, we wanted to make it work as much as will do in production).
    18 | 19 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 20 | You will also see requests logs in the console, using [https://github.com/dariomac/dm-logger](https://github.com/dariomac/dm-logger).
    21 | 22 | If you find this repo and didn't read the full article, you can do it here: [https://www.vairix.com/tech-blog/server-side-rendering-ssr-of-create-react-app-cra-app-in-2020](https://www.vairix.com/tech-blog/server-side-rendering-ssr-of-create-react-app-cra-app-in-2020) 23 | 24 | ## Create-React-App default scripts 25 | 26 | ### `yarn start` 27 | 28 | Runs the app in the development mode.
    29 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 30 | 31 | The page will reload if you make edits.
    32 | You will also see any lint errors in the console. 33 | 34 | ### `yarn test` 35 | 36 | Launches the test runner in the interactive watch mode.
    37 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 38 | 39 | ### `yarn build` 40 | 41 | Builds the app for production to the `build` folder.
    42 | It correctly bundles React in production mode and optimizes the build for the best performance. 43 | 44 | The build is minified and the filenames include the hashes.
    45 | Your app is ready to be deployed! 46 | 47 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 48 | 49 | ### `yarn eject` 50 | 51 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 52 | 53 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 54 | 55 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 56 | 57 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 58 | 59 | ## Learn More 60 | 61 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 62 | 63 | To learn React, check out the [React documentation](https://reactjs.org/). 64 | 65 | ### Code Splitting 66 | 67 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 68 | 69 | ### Analyzing the Bundle Size 70 | 71 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 72 | 73 | ### Making a Progressive Web App 74 | 75 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 76 | 77 | ### Advanced Configuration 78 | 79 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 80 | 81 | ### Deployment 82 | 83 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 84 | 85 | ### `yarn build` fails to minify 86 | 87 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 88 | -------------------------------------------------------------------------------- /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 https://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.0/8 are 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 https://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 https://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 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready.then(registration => { 134 | registration.unregister(); 135 | }); 136 | } 137 | } 138 | --------------------------------------------------------------------------------