├── public ├── favicon.ico ├── manifest.json └── index.html ├── src ├── Title.js ├── index.js ├── lib │ └── calculate-pizzas-needed.js ├── Result.js ├── Input.js ├── style.css └── Application.js ├── config ├── custom-react-scripts │ ├── customizers │ │ ├── babel-presets.js │ │ ├── babel-plugins.js │ │ ├── webpack-plugins.js │ │ └── webpack-loaders.js │ ├── options │ │ ├── postcss-options.js │ │ └── extract-text-plugin-options.js │ ├── utils │ │ └── map-object.js │ ├── config.js │ └── webpack-config │ │ └── style-loader.js ├── jest │ ├── fileTransform.js │ └── cssTransform.js ├── polyfills.js ├── paths.js ├── env.js ├── webpackDevServer.config.js ├── webpack.config.dev.js └── webpack.config.prod.js ├── .env ├── .gitignore ├── scripts ├── test.js ├── getProcessForPort.js ├── modify-readmes.js ├── start.js └── build.js ├── package.json └── README.md /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stevekinney/pizza-calculator/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /src/Title.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default ({ name }) =>

Pizza Calculator

; 4 | -------------------------------------------------------------------------------- /config/custom-react-scripts/customizers/babel-presets.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | BABEL_STAGE_0: { 3 | get: () => require.resolve('babel-preset-stage-0'), 4 | }, 5 | }; 6 | -------------------------------------------------------------------------------- /config/custom-react-scripts/customizers/babel-plugins.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | DECORATORS: { 3 | get: () => require.resolve('babel-plugin-transform-decorators-legacy'), 4 | }, 5 | }; 6 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from 'react-dom'; 3 | 4 | import Application from './Application'; 5 | 6 | import './style.css'; 7 | 8 | render(, document.getElementById('root')); 9 | -------------------------------------------------------------------------------- /config/custom-react-scripts/customizers/webpack-plugins.js: -------------------------------------------------------------------------------- 1 | const DashboardPlugin = require('webpack-dashboard/plugin'); 2 | 3 | module.exports = { 4 | WEBPACK_DASHBOARD: { 5 | get: () => new DashboardPlugin(), 6 | }, 7 | }; 8 | -------------------------------------------------------------------------------- /src/lib/calculate-pizzas-needed.js: -------------------------------------------------------------------------------- 1 | export default function calculatePizzasNeeded( 2 | numberOfPeople, 3 | slicesPerPerson, 4 | slicesPerPizza = 8, 5 | ) { 6 | return Math.ceil(numberOfPeople * slicesPerPerson / slicesPerPizza); 7 | } 8 | -------------------------------------------------------------------------------- /src/Result.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | const Result = ({ amount }) => { 4 | const pizzas = amount === 1 ? 'pizza' : 'pizzas'; 5 | return ( 6 |
7 |

8 | You will need to order {amount} {pizzas}. 9 |

10 |
11 | ); 12 | }; 13 | 14 | export default Result; 15 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | REACT_APP_DECORATORS = true; 2 | REACT_APP_BABEL_STAGE_0 = true; 3 | 4 | REACT_APP_SASS = true; 5 | REACT_APP_LESS = true; 6 | REACT_APP_STYLUS = true; 7 | 8 | REACT_APP_CSS_MODULES = true; 9 | REACT_APP_SASS_MODULES = true; 10 | REACT_APP_STYLUS_MODULES = true; 11 | REACT_APP_LESS_MODULES = true; 12 | 13 | REACT_APP_WEBPACK_DASHBOARD = true; 14 | -------------------------------------------------------------------------------- /config/custom-react-scripts/options/postcss-options.js: -------------------------------------------------------------------------------- 1 | const autoprefixer = require('autoprefixer'); 2 | 3 | module.exports = { 4 | ident: 'postcss', 5 | plugins: () => [ 6 | require('postcss-flexbugs-fixes'), 7 | autoprefixer({ 8 | browsers: ['>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9'], 9 | flexbox: 'no-2009', 10 | }), 11 | ], 12 | }; 13 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React 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 | } 16 | -------------------------------------------------------------------------------- /config/jest/fileTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | 5 | // This is a custom Jest transformer turning file imports into filenames. 6 | // http://facebook.github.io/jest/docs/tutorial-webpack.html 7 | 8 | module.exports = { 9 | process(src, filename) { 10 | return `module.exports = ${JSON.stringify(path.basename(filename))};`; 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /config/jest/cssTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // This is a custom Jest transformer turning style imports into empty objects. 4 | // http://facebook.github.io/jest/docs/tutorial-webpack.html 5 | 6 | module.exports = { 7 | process() { 8 | return 'module.exports = {};'; 9 | }, 10 | getCacheKey() { 11 | // The output is always the same. 12 | return 'cssTransform'; 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /config/custom-react-scripts/utils/map-object.js: -------------------------------------------------------------------------------- 1 | module.exports = function mapObject(obj, fn, toArray) { 2 | return Object.keys(obj).reduce(function(final, key) { 3 | var result = fn(obj[key], key); 4 | if (!result) { 5 | return final; 6 | } 7 | if (toArray) { 8 | final.push(result); 9 | } 10 | final[key] = result; 11 | return final; 12 | }, toArray ? [] : {}); 13 | }; 14 | -------------------------------------------------------------------------------- /src/Input.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | const Input = ({ label, value, max, min, type, onChange }) => { 4 | return ( 5 | 16 | ); 17 | }; 18 | 19 | export default Input; 20 | -------------------------------------------------------------------------------- /config/custom-react-scripts/options/extract-text-plugin-options.js: -------------------------------------------------------------------------------- 1 | const paths = require('../../paths'); 2 | 3 | const publicPath = paths.servedPath; 4 | const cssFilename = 'static/css/[name].[contenthash:8].css'; 5 | const shouldUseRelativeAssetPaths = publicPath === './'; 6 | 7 | module.exports = shouldUseRelativeAssetPaths 8 | ? // Making sure that the publicPath goes back to to build folder. 9 | { publicPath: Array(cssFilename.split('/').length).join('../') } 10 | : {}; 11 | -------------------------------------------------------------------------------- /config/polyfills.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | if (typeof Promise === 'undefined') { 4 | // Rejection tracking prevents a common issue where React gets into an 5 | // inconsistent state due to an error, but it gets swallowed by a Promise, 6 | // and the user has no idea what causes React's erratic future behavior. 7 | require('promise/lib/rejection-tracking').enable(); 8 | window.Promise = require('promise/lib/es6-extensions.js'); 9 | } 10 | 11 | // fetch() polyfill for making API calls. 12 | require('whatwg-fetch'); 13 | 14 | // Object.assign() is commonly used with React. 15 | // It will use the native implementation if it's present and isn't buggy. 16 | Object.assign = require('object-assign'); 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | # See https://help.github.com/ignore-files/ for more about ignoring files. 23 | 24 | # dependencies 25 | /node_modules 26 | 27 | # testing 28 | /coverage 29 | 30 | # production 31 | /build 32 | 33 | # misc 34 | .DS_Store 35 | .env.local 36 | .env.development.local 37 | .env.test.local 38 | .env.production.local 39 | 40 | npm-debug.log* 41 | yarn-debug.log* 42 | yarn-error.log* 43 | -------------------------------------------------------------------------------- /scripts/test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'test'; 5 | process.env.NODE_ENV = 'test'; 6 | process.env.PUBLIC_URL = ''; 7 | 8 | // Makes the script crash on unhandled rejections instead of silently 9 | // ignoring them. In the future, promise rejections that are not handled will 10 | // terminate the Node.js process with a non-zero exit code. 11 | process.on('unhandledRejection', err => { 12 | throw err; 13 | }); 14 | 15 | // Ensure environment variables are read. 16 | require('../config/env'); 17 | 18 | const jest = require('jest'); 19 | const argv = process.argv.slice(2); 20 | 21 | // Watch unless on CI or in coverage mode 22 | if (!process.env.CI && argv.indexOf('--coverage') < 0) { 23 | argv.push('--watch'); 24 | } 25 | 26 | 27 | jest.run(argv); 28 | -------------------------------------------------------------------------------- /config/custom-react-scripts/config.js: -------------------------------------------------------------------------------- 1 | const mapObject = require('./utils/map-object'); 2 | 3 | const customizers = { 4 | babelPlugins: require('./customizers/babel-plugins'), 5 | babelPresets: require('./customizers/babel-presets'), 6 | webpackLoaders: require('./customizers/webpack-loaders'), 7 | webpackPlugins: require('./customizers/webpack-plugins'), 8 | }; 9 | 10 | module.exports = getCustomConfig = (isDev = true) => { 11 | var env = env || {}; 12 | const result = mapObject(customizers, group => { 13 | return mapObject( 14 | group, 15 | (customizer, key) => { 16 | const envValue = process.env['REACT_APP_' + key]; 17 | const activeEnvValue = env && envValue && envValue !== 'false'; 18 | return (activeEnvValue || customizer.default) && customizer.get(isDev); 19 | }, 20 | true 21 | ); 22 | }); 23 | return result; 24 | }; 25 | -------------------------------------------------------------------------------- /src/style.css: -------------------------------------------------------------------------------- 1 | html, 2 | * { 3 | box-sizing: border-box; 4 | } 5 | 6 | body, 7 | input { 8 | font: menu; 9 | } 10 | 11 | label { 12 | display: block; 13 | margin-bottom: 10px; 14 | } 15 | 16 | input { 17 | padding: 0.5em; 18 | border: 1px solid #f32e5b; 19 | background-color: #fbbfcd; 20 | } 21 | 22 | label > input { 23 | margin-left: 10px; 24 | } 25 | 26 | button, 27 | .button, 28 | input[type='submit'] { 29 | background-color: #f32e5b; 30 | border: 1px solid #e10d3d; 31 | color: white; 32 | padding: 0.5em; 33 | transition: all 0.2s; 34 | } 35 | 36 | button:hover, 37 | .button:hover, 38 | input[type='submit']:hover { 39 | background-color: #f65e81; 40 | } 41 | 42 | button:active, 43 | .button:active, 44 | input[type='submit']:active { 45 | background-color: #f4466e; 46 | } 47 | 48 | button.full-width, 49 | .button.full-width, 50 | input[type='submit'].full-width { 51 | width: 100%; 52 | margin: 1em 0; 53 | } 54 | 55 | .Application { 56 | margin: auto; 57 | max-width: 400px; 58 | text-align: center; 59 | } 60 | 61 | .Result { 62 | font-size: 1.8em; 63 | } 64 | -------------------------------------------------------------------------------- /config/custom-react-scripts/customizers/webpack-loaders.js: -------------------------------------------------------------------------------- 1 | const styleLoader = require('../webpack-config/style-loader'); 2 | const sassLoader = require.resolve('sass-loader'); 3 | const lessLoader = require.resolve('less-loader'); 4 | const stylusLoader = require.resolve('stylus-loader'); 5 | 6 | module.exports = { 7 | CSS: { 8 | default: true, 9 | get: styleLoader(undefined, /\.css$/, /\.module\.css$/), 10 | }, 11 | SASS: { 12 | get: styleLoader(sassLoader, /\.s[ac]ss$/, /\.module\.s[ac]ss$/), 13 | }, 14 | LESS: { 15 | get: styleLoader(lessLoader, /\.less$/, /\.module\.less$/), 16 | }, 17 | STYLUS: { 18 | get: styleLoader(stylusLoader, /\.styl/, /\.module\.styl/), 19 | }, 20 | STYLUS_MODULES: { 21 | get: styleLoader(stylusLoader, /\.module\.styl/, undefined, true), 22 | }, 23 | LESS_MODULES: { 24 | get: styleLoader(lessLoader, /\.module\.less$/, undefined, true), 25 | }, 26 | SASS_MODULES: { 27 | get: styleLoader(sassLoader, /\.module\.s[ac]ss$/, undefined, true), 28 | }, 29 | CSS_MODULES: { 30 | get: styleLoader(undefined, /\.module\.css$/, undefined, true), 31 | }, 32 | }; 33 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 22 | React App 23 | 24 | 25 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/Application.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | 3 | import Title from './Title'; 4 | import Input from './Input'; 5 | import Result from './Result'; 6 | 7 | import calculatePizzasNeeded from './lib/calculate-pizzas-needed'; 8 | 9 | const initialState = { 10 | numberOfPeople: 10, 11 | slicesPerPerson: 2, 12 | }; 13 | 14 | export default class Application extends Component { 15 | state = { ...initialState }; 16 | 17 | updateNumberOfPeople = event => { 18 | const numberOfPeople = parseInt(event.target.value, 10); 19 | this.setState({ numberOfPeople }); 20 | }; 21 | 22 | updateSlicesPerPerson = event => { 23 | const slicesPerPerson = parseInt(event.target.value, 10); 24 | this.setState({ slicesPerPerson }); 25 | }; 26 | 27 | reset = event => { 28 | this.setState({ ...initialState }); 29 | }; 30 | 31 | render() { 32 | const { numberOfPeople, slicesPerPerson } = this.state; 33 | const numberOfPizzas = calculatePizzasNeeded( 34 | numberOfPeople, 35 | slicesPerPerson, 36 | ); 37 | 38 | return ( 39 |
40 | 41 | <Input 42 | label="Number of Guests" 43 | type="number" 44 | min={0} 45 | value={numberOfPeople} 46 | onChange={this.updateNumberOfPeople} 47 | /> 48 | <Input 49 | label="Slices Per Person" 50 | type="number" 51 | min={0} 52 | value={slicesPerPerson} 53 | onChange={this.updateSlicesPerPerson} 54 | /> 55 | <Result amount={numberOfPizzas} /> 56 | <button className="full-width" onClick={this.reset}> 57 | Reset 58 | </button> 59 | </div> 60 | ); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /scripts/getProcessForPort.js: -------------------------------------------------------------------------------- 1 | var chalk = require('chalk'); 2 | var execSync = require('child_process').execSync; 3 | var path = require('path'); 4 | 5 | var execOptions = { 6 | encoding: 'utf8', 7 | stdio: [ 8 | 'pipe', // stdin (default) 9 | 'pipe', // stdout (default) 10 | 'ignore' //stderr 11 | ] 12 | }; 13 | 14 | function isProcessAReactApp(processCommand) { 15 | return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand); 16 | } 17 | 18 | function getProcessIdOnPort(port) { 19 | return execSync('lsof -i:' + port + ' -P -t -sTCP:LISTEN', execOptions).trim(); 20 | } 21 | 22 | function getPackageNameInDirectory(directory) { 23 | var packagePath = path.join(directory.trim(), 'package.json'); 24 | 25 | try { 26 | return require(packagePath).name; 27 | } catch(e) { 28 | return null; 29 | } 30 | 31 | } 32 | 33 | function getProcessCommand(processId, processDirectory) { 34 | var command = execSync('ps -o command -p ' + processId + ' | sed -n 2p', execOptions); 35 | 36 | if (isProcessAReactApp(command)) { 37 | const packageName = getPackageNameInDirectory(processDirectory); 38 | return (packageName) ? packageName + '\n' : command; 39 | } else { 40 | return command; 41 | } 42 | 43 | } 44 | 45 | function getDirectoryOfProcessById(processId) { 46 | return execSync('lsof -p '+ processId + ' | grep cwd | awk \'{print $9}\'', execOptions).trim(); 47 | } 48 | 49 | function getProcessForPort(port) { 50 | try { 51 | var processId = getProcessIdOnPort(port); 52 | var directory = getDirectoryOfProcessById(processId); 53 | var command = getProcessCommand(processId, directory); 54 | return chalk.cyan(command) + chalk.blue(' in ') + chalk.cyan(directory); 55 | } catch(e) { 56 | return null; 57 | } 58 | } 59 | 60 | module.exports = getProcessForPort; 61 | -------------------------------------------------------------------------------- /config/custom-react-scripts/webpack-config/style-loader.js: -------------------------------------------------------------------------------- 1 | const postCssOptions = require('../options/postcss-options'); 2 | const extractTextPluginOptions = require('../options/extract-text-plugin-options'); 3 | const ExtractTextPlugin = require('extract-text-webpack-plugin'); 4 | const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; 5 | 6 | module.exports = (loader, test, exclude, modules) => isDev => { 7 | let loaders = isDev 8 | ? [ 9 | { 10 | loader: require.resolve('style-loader'), 11 | }, 12 | ] 13 | : []; 14 | 15 | loaders = loaders.concat([ 16 | { 17 | loader: require.resolve('css-loader'), 18 | options: Object.assign( 19 | { minimize: !isDev, sourceMap: shouldUseSourceMap }, 20 | { importLoaders: 1 }, 21 | modules === true 22 | ? { 23 | localIdentName: '[sha512:hash:base32]-[name]-[local]', 24 | modules: true, 25 | } 26 | : {} 27 | ), 28 | }, 29 | { 30 | loader: require.resolve('postcss-loader'), 31 | options: Object.assign( 32 | {}, 33 | { sourceMap: shouldUseSourceMap }, 34 | postCssOptions 35 | ), 36 | }, 37 | ]); 38 | 39 | if (loader) { 40 | loaders.push({ 41 | loader, 42 | options: { 43 | sourceMap: shouldUseSourceMap, 44 | }, 45 | }); 46 | } 47 | 48 | if (isDev) { 49 | return { 50 | test, 51 | exclude, 52 | use: loaders, 53 | }; 54 | } 55 | 56 | return { 57 | test, 58 | exclude, 59 | loader: ExtractTextPlugin.extract( 60 | Object.assign( 61 | { 62 | fallback: require.resolve('style-loader'), 63 | use: loaders, 64 | }, 65 | extractTextPluginOptions 66 | ) 67 | ), 68 | }; 69 | }; 70 | -------------------------------------------------------------------------------- /scripts/modify-readmes.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs-extra'); 2 | var path = require('path'); 3 | const args = process.argv; 4 | 5 | //read md file as text 6 | require.extensions['.md'] = function (module, filename) { 7 | module.exports = fs.readFileSync(filename, 'utf8'); 8 | }; 9 | 10 | var filenames = { 11 | BACKUP: 'README_BACKUP.md', 12 | README: 'README.MD', 13 | CUSTOM_README: 'CUSTOM_README.md' 14 | }; 15 | 16 | var paths = { 17 | //original 18 | RSreadme: path.join(__dirname, '..', filenames.README), 19 | CRAreadme: path.join(__dirname, '../../../', filenames.README), 20 | //custom 21 | customReadme: path.join(__dirname, '../bin/', filenames.CUSTOM_README), 22 | //backup 23 | RSbackup: path.join(__dirname, '..', filenames.BACKUP), 24 | CRAbackup: path.join(__dirname, '../../../', filenames.BACKUP) 25 | }; 26 | 27 | function backupOriginal() { 28 | fs.copySync(paths.RSreadme, paths.RSbackup); 29 | fs.copySync(paths.CRAreadme, paths.CRAbackup); 30 | } 31 | 32 | function deleteBackup() { 33 | fs.removeSync(paths.RSbackup); 34 | fs.removeSync(paths.CRAbackup); 35 | } 36 | 37 | function deleteOriginal() { 38 | fs.removeSync(paths.RSreadme); 39 | fs.removeSync(paths.CRAreadme); 40 | } 41 | 42 | function placeCustom() { 43 | fs.copySync(paths.customReadme, paths.RSreadme); 44 | fs.copySync(paths.customReadme, paths.CRAreadme); 45 | } 46 | 47 | function placeOriginal() { 48 | fs.copySync(paths.RSbackup, paths.RSreadme); 49 | fs.copySync(paths.CRAbackup, paths.CRAreadme); 50 | } 51 | 52 | //will set custom readmes 53 | function setCustom() { 54 | backupOriginal(); 55 | deleteOriginal(); 56 | placeCustom(); 57 | } 58 | 59 | //will revert original readmes 60 | function revertOriginalBackups() { 61 | deleteOriginal(); 62 | placeOriginal(); 63 | deleteBackup(); 64 | } 65 | 66 | var argFunctionMap = { 67 | '--custom': setCustom, 68 | '--original': revertOriginalBackups, 69 | } 70 | 71 | if (args && args.length >= 2) { 72 | var command = argFunctionMap[args[2]]; 73 | command && command(); 74 | } 75 | -------------------------------------------------------------------------------- /config/paths.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const fs = require('fs'); 5 | const url = require('url'); 6 | 7 | // Make sure any symlinks in the project folder are resolved: 8 | // https://github.com/facebookincubator/create-react-app/issues/637 9 | const appDirectory = fs.realpathSync(process.cwd()); 10 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 11 | 12 | const envPublicUrl = process.env.PUBLIC_URL; 13 | 14 | function ensureSlash(path, needsSlash) { 15 | const hasSlash = path.endsWith('/'); 16 | if (hasSlash && !needsSlash) { 17 | return path.substr(path, path.length - 1); 18 | } else if (!hasSlash && needsSlash) { 19 | return `${path}/`; 20 | } else { 21 | return path; 22 | } 23 | } 24 | 25 | const getPublicUrl = appPackageJson => 26 | envPublicUrl || require(appPackageJson).homepage; 27 | 28 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer 29 | // "public path" at which the app is served. 30 | // Webpack needs to know it to put the right <script> hrefs into HTML even in 31 | // single-page apps that may serve index.html for nested URLs like /todos/42. 32 | // We can't use a relative path in HTML because we don't want to load something 33 | // like /todos/42/static/js/bundle.7289d.js. We have to know the root. 34 | function getServedPath(appPackageJson) { 35 | const publicUrl = getPublicUrl(appPackageJson); 36 | const servedUrl = 37 | envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/'); 38 | return ensureSlash(servedUrl, true); 39 | } 40 | 41 | // config after eject: we're in ./config/ 42 | module.exports = { 43 | dotenv: resolveApp('.env'), 44 | appBuild: resolveApp('build'), 45 | appPublic: resolveApp('public'), 46 | appHtml: resolveApp('public/index.html'), 47 | appIndexJs: resolveApp('src/index.js'), 48 | appPackageJson: resolveApp('package.json'), 49 | appSrc: resolveApp('src'), 50 | yarnLockFile: resolveApp('yarn.lock'), 51 | testsSetup: resolveApp('src/setupTests.js'), 52 | appNodeModules: resolveApp('node_modules'), 53 | publicUrl: getPublicUrl(resolveApp('package.json')), 54 | servedPath: getServedPath(resolveApp('package.json')), 55 | }; 56 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pizza-calculator", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "autoprefixer": "7.1.2", 7 | "babel-core": "6.25.0", 8 | "babel-eslint": "7.2.3", 9 | "babel-jest": "20.0.3", 10 | "babel-loader": "7.1.1", 11 | "babel-plugin-transform-decorators": "^6.24.1", 12 | "babel-plugin-transform-decorators-legacy": "^1.3.4", 13 | "babel-preset-react-app": "^3.0.2", 14 | "babel-preset-stage-0": "^6.24.1", 15 | "babel-runtime": "6.23.0", 16 | "case-sensitive-paths-webpack-plugin": "2.1.1", 17 | "chalk": "1.1.3", 18 | "css-loader": "0.28.4", 19 | "dotenv": "4.0.0", 20 | "eslint": "4.4.1", 21 | "eslint-config-react-app": "^2.0.0", 22 | "eslint-loader": "1.9.0", 23 | "eslint-plugin-flowtype": "2.35.0", 24 | "eslint-plugin-import": "2.7.0", 25 | "eslint-plugin-jsx-a11y": "5.1.1", 26 | "eslint-plugin-react": "7.1.0", 27 | "extract-text-webpack-plugin": "3.0.0", 28 | "file-loader": "0.11.2", 29 | "flux": "^3.1.3", 30 | "fs-extra": "3.0.1", 31 | "html-webpack-plugin": "2.29.0", 32 | "idb": "^2.0.4", 33 | "jest": "20.0.4", 34 | "less": "^2.7.2", 35 | "less-loader": "^4.0.5", 36 | "localforage": "^1.5.3", 37 | "lodash": "^4.17.4", 38 | "mobx": "3.3.1", 39 | "mobx-react": "4.3.4", 40 | "mobx-state-tree": "^1.1.0", 41 | "node-sass": "^4.5.3", 42 | "object-assign": "4.1.1", 43 | "postcss-flexbugs-fixes": "3.2.0", 44 | "postcss-loader": "2.0.6", 45 | "promise": "8.0.1", 46 | "react": "^16.1.0", 47 | "react-dev-utils": "^3.1.0", 48 | "react-dom": "^16.1.0", 49 | "react-error-overlay": "^1.0.10", 50 | "react-redux": "5.0.6", 51 | "redux": "3.7.2", 52 | "redux-saga": "^0.16.0", 53 | "redux-thunk": "^2.2.0", 54 | "sass-loader": "^6.0.6", 55 | "style-loader": "0.18.2", 56 | "stylus": "^0.54.5", 57 | "stylus-loader": "^3.0.1", 58 | "sw-precache-webpack-plugin": "0.11.4", 59 | "url-loader": "0.5.9", 60 | "webpack": "3.5.1", 61 | "webpack-dashboard": "^1.0.0-2", 62 | "webpack-dev-server": "2.7.1", 63 | "webpack-manifest-plugin": "1.2.1", 64 | "whatwg-fetch": "2.0.3" 65 | }, 66 | "scripts": { 67 | "start": "node scripts/start.js", 68 | "build": "node scripts/build.js", 69 | "test": "node scripts/test.js --env=jsdom" 70 | }, 71 | "jest": { 72 | "collectCoverageFrom": ["src/**/*.{js,jsx}"], 73 | "setupFiles": ["<rootDir>/config/polyfills.js"], 74 | "testMatch": [ 75 | "<rootDir>/src/**/__tests__/**/*.js?(x)", 76 | "<rootDir>/src/**/?(*.)(spec|test).js?(x)" 77 | ], 78 | "testEnvironment": "node", 79 | "testURL": "http://localhost", 80 | "transform": { 81 | "^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest", 82 | "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js", 83 | "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js" 84 | }, 85 | "transformIgnorePatterns": ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"], 86 | "moduleNameMapper": { 87 | "^react-native$": "react-native-web" 88 | }, 89 | "moduleFileExtensions": ["web.js", "js", "json", "web.jsx", "jsx", "node"] 90 | }, 91 | "babel": { 92 | "plugins": ["transform-decorators"], 93 | "presets": ["react-app"] 94 | }, 95 | "eslintConfig": { 96 | "extends": "react-app" 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /scripts/start.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'development'; 5 | process.env.NODE_ENV = 'development'; 6 | 7 | // Makes the script crash on unhandled rejections instead of silently 8 | // ignoring them. In the future, promise rejections that are not handled will 9 | // terminate the Node.js process with a non-zero exit code. 10 | process.on('unhandledRejection', err => { 11 | throw err; 12 | }); 13 | 14 | // Ensure environment variables are read. 15 | require('../config/env'); 16 | 17 | const fs = require('fs'); 18 | const chalk = require('chalk'); 19 | const webpack = require('webpack'); 20 | const WebpackDevServer = require('webpack-dev-server'); 21 | const clearConsole = require('react-dev-utils/clearConsole'); 22 | const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); 23 | const { 24 | choosePort, 25 | createCompiler, 26 | prepareProxy, 27 | prepareUrls, 28 | } = require('react-dev-utils/WebpackDevServerUtils'); 29 | const openBrowser = require('react-dev-utils/openBrowser'); 30 | const paths = require('../config/paths'); 31 | const config = require('../config/webpack.config.dev'); 32 | const createDevServerConfig = require('../config/webpackDevServer.config'); 33 | 34 | const useYarn = fs.existsSync(paths.yarnLockFile); 35 | const isInteractive = process.stdout.isTTY; 36 | 37 | // Warn and crash if required files are missing 38 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 39 | process.exit(1); 40 | } 41 | 42 | // Tools like Cloud9 rely on this. 43 | const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; 44 | const HOST = process.env.HOST || '0.0.0.0'; 45 | 46 | // We attempt to use the default port but if it is busy, we offer the user to 47 | // run on a different port. `detect()` Promise resolves to the next free port. 48 | choosePort(HOST, DEFAULT_PORT) 49 | .then(port => { 50 | if (port == null) { 51 | // We have not found a port. 52 | return; 53 | } 54 | const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; 55 | const appName = require(paths.appPackageJson).name; 56 | const urls = prepareUrls(protocol, HOST, port); 57 | // Create a webpack compiler that is configured with custom messages. 58 | const compiler = createCompiler(webpack, config, appName, urls, useYarn); 59 | // Load proxy config 60 | const proxySetting = require(paths.appPackageJson).proxy; 61 | const proxyConfig = prepareProxy(proxySetting, paths.appPublic); 62 | // Serve webpack assets generated by the compiler over a web sever. 63 | const serverConfig = createDevServerConfig( 64 | proxyConfig, 65 | urls.lanUrlForConfig 66 | ); 67 | const devServer = new WebpackDevServer(compiler, serverConfig); 68 | // Launch WebpackDevServer. 69 | devServer.listen(port, HOST, err => { 70 | if (err) { 71 | return console.log(err); 72 | } 73 | if (isInteractive) { 74 | clearConsole(); 75 | } 76 | console.log(chalk.cyan('Starting the development server...\n')); 77 | openBrowser(urls.localUrlForBrowser); 78 | }); 79 | 80 | ['SIGINT', 'SIGTERM'].forEach(function(sig) { 81 | process.on(sig, function() { 82 | devServer.close(); 83 | process.exit(); 84 | }); 85 | }); 86 | }) 87 | .catch(err => { 88 | if (err && err.message) { 89 | console.log(err.message); 90 | } 91 | process.exit(1); 92 | }); 93 | -------------------------------------------------------------------------------- /config/env.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | 7 | // Make sure that including paths.js after env.js will read .env variables. 8 | delete require.cache[require.resolve('./paths')]; 9 | 10 | const NODE_ENV = process.env.NODE_ENV; 11 | if (!NODE_ENV) { 12 | throw new Error( 13 | 'The NODE_ENV environment variable is required but was not specified.' 14 | ); 15 | } 16 | 17 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use 18 | var dotenvFiles = [ 19 | `${paths.dotenv}.${NODE_ENV}.local`, 20 | `${paths.dotenv}.${NODE_ENV}`, 21 | // Don't include `.env.local` for `test` environment 22 | // since normally you expect tests to produce the same 23 | // results for everyone 24 | NODE_ENV !== 'test' && `${paths.dotenv}.local`, 25 | paths.dotenv, 26 | ].filter(Boolean); 27 | 28 | // Load environment variables from .env* files. Suppress warnings using silent 29 | // if this file is missing. dotenv will never modify any environment variables 30 | // that have already been set. 31 | // https://github.com/motdotla/dotenv 32 | dotenvFiles.forEach(dotenvFile => { 33 | if (fs.existsSync(dotenvFile)) { 34 | require('dotenv').config({ 35 | path: dotenvFile, 36 | }); 37 | } 38 | }); 39 | 40 | // We support resolving modules according to `NODE_PATH`. 41 | // This lets you use absolute paths in imports inside large monorepos: 42 | // https://github.com/facebookincubator/create-react-app/issues/253. 43 | // It works similar to `NODE_PATH` in Node itself: 44 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders 45 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. 46 | // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. 47 | // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421 48 | // We also resolve them to make sure all tools using them work consistently. 49 | const appDirectory = fs.realpathSync(process.cwd()); 50 | process.env.NODE_PATH = (process.env.NODE_PATH || '') 51 | .split(path.delimiter) 52 | .filter(folder => folder && !path.isAbsolute(folder)) 53 | .map(folder => path.resolve(appDirectory, folder)) 54 | .join(path.delimiter); 55 | 56 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be 57 | // injected into the application via DefinePlugin in Webpack configuration. 58 | const REACT_APP = /^REACT_APP_/i; 59 | 60 | function getClientEnvironment(publicUrl) { 61 | const raw = Object.keys(process.env) 62 | .filter(key => REACT_APP.test(key)) 63 | .reduce( 64 | (env, key) => { 65 | env[key] = process.env[key]; 66 | return env; 67 | }, 68 | { 69 | // Useful for determining whether we’re running in production mode. 70 | // Most importantly, it switches React into the correct mode. 71 | NODE_ENV: process.env.NODE_ENV || 'development', 72 | // Useful for resolving the correct path to static assets in `public`. 73 | // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />. 74 | // This should only be used as an escape hatch. Normally you would put 75 | // images into the `src` and `import` them in code to get their paths. 76 | PUBLIC_URL: publicUrl, 77 | } 78 | ); 79 | // Stringify all values so we can feed into Webpack DefinePlugin 80 | const stringified = { 81 | 'process.env': Object.keys(raw).reduce((env, key) => { 82 | env[key] = JSON.stringify(raw[key]); 83 | return env; 84 | }, {}), 85 | }; 86 | 87 | return { raw, stringified }; 88 | } 89 | 90 | module.exports = getClientEnvironment; 91 | -------------------------------------------------------------------------------- /config/webpackDevServer.config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const errorOverlayMiddleware = require('react-error-overlay/middleware'); 4 | const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware'); 5 | const config = require('./webpack.config.dev'); 6 | const paths = require('./paths'); 7 | 8 | const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; 9 | const host = process.env.HOST || '0.0.0.0'; 10 | 11 | module.exports = function(proxy, allowedHost) { 12 | return { 13 | // WebpackDevServer 2.4.3 introduced a security fix that prevents remote 14 | // websites from potentially accessing local content through DNS rebinding: 15 | // https://github.com/webpack/webpack-dev-server/issues/887 16 | // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a 17 | // However, it made several existing use cases such as development in cloud 18 | // environment or subdomains in development significantly more complicated: 19 | // https://github.com/facebookincubator/create-react-app/issues/2271 20 | // https://github.com/facebookincubator/create-react-app/issues/2233 21 | // While we're investigating better solutions, for now we will take a 22 | // compromise. Since our WDS configuration only serves files in the `public` 23 | // folder we won't consider accessing them a vulnerability. However, if you 24 | // use the `proxy` feature, it gets more dangerous because it can expose 25 | // remote code execution vulnerabilities in backends like Django and Rails. 26 | // So we will disable the host check normally, but enable it if you have 27 | // specified the `proxy` setting. Finally, we let you override it if you 28 | // really know what you're doing with a special environment variable. 29 | disableHostCheck: 30 | !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true', 31 | // Enable gzip compression of generated files. 32 | compress: true, 33 | // Silence WebpackDevServer's own logs since they're generally not useful. 34 | // It will still show compile warnings and errors with this setting. 35 | clientLogLevel: 'none', 36 | // By default WebpackDevServer serves physical files from current directory 37 | // in addition to all the virtual build products that it serves from memory. 38 | // This is confusing because those files won’t automatically be available in 39 | // production build folder unless we copy them. However, copying the whole 40 | // project directory is dangerous because we may expose sensitive files. 41 | // Instead, we establish a convention that only files in `public` directory 42 | // get served. Our build script will copy `public` into the `build` folder. 43 | // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%: 44 | // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 45 | // In JavaScript code, you can access it with `process.env.PUBLIC_URL`. 46 | // Note that we only recommend to use `public` folder as an escape hatch 47 | // for files like `favicon.ico`, `manifest.json`, and libraries that are 48 | // for some reason broken when imported through Webpack. If you just want to 49 | // use an image, put it in `src` and `import` it from JavaScript instead. 50 | contentBase: paths.appPublic, 51 | // By default files from `contentBase` will not trigger a page reload. 52 | watchContentBase: true, 53 | // Enable hot reloading server. It will provide /sockjs-node/ endpoint 54 | // for the WebpackDevServer client so it can learn when the files were 55 | // updated. The WebpackDevServer client is included as an entry point 56 | // in the Webpack development configuration. Note that only changes 57 | // to CSS are currently hot reloaded. JS changes will refresh the browser. 58 | hot: true, 59 | // It is important to tell WebpackDevServer to use the same "root" path 60 | // as we specified in the config. In development, we always serve from /. 61 | publicPath: config.output.publicPath, 62 | // WebpackDevServer is noisy by default so we emit custom message instead 63 | // by listening to the compiler events with `compiler.plugin` calls above. 64 | quiet: true, 65 | // Reportedly, this avoids CPU overload on some systems. 66 | // https://github.com/facebookincubator/create-react-app/issues/293 67 | watchOptions: { 68 | ignored: /node_modules/, 69 | }, 70 | // Enable HTTPS if the HTTPS environment variable is set to 'true' 71 | https: protocol === 'https', 72 | host: host, 73 | overlay: false, 74 | historyApiFallback: { 75 | // Paths with dots should still use the history fallback. 76 | // See https://github.com/facebookincubator/create-react-app/issues/387. 77 | disableDotRule: true, 78 | }, 79 | public: allowedHost, 80 | proxy, 81 | setup(app) { 82 | // This lets us open files from the runtime error overlay. 83 | app.use(errorOverlayMiddleware()); 84 | // This service worker file is effectively a 'no-op' that will reset any 85 | // previous service worker registered for the same host:port combination. 86 | // We do this in development to avoid hitting the production cache if 87 | // it used the same host and port. 88 | // https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432 89 | app.use(noopServiceWorkerMiddleware()); 90 | }, 91 | }; 92 | }; 93 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'production'; 5 | process.env.NODE_ENV = 'production'; 6 | 7 | // Makes the script crash on unhandled rejections instead of silently 8 | // ignoring them. In the future, promise rejections that are not handled will 9 | // terminate the Node.js process with a non-zero exit code. 10 | process.on('unhandledRejection', err => { 11 | throw err; 12 | }); 13 | 14 | // Ensure environment variables are read. 15 | require('../config/env'); 16 | 17 | const path = require('path'); 18 | const chalk = require('chalk'); 19 | const fs = require('fs-extra'); 20 | const webpack = require('webpack'); 21 | const config = require('../config/webpack.config.prod'); 22 | const paths = require('../config/paths'); 23 | const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); 24 | const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); 25 | const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); 26 | const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); 27 | const printBuildError = require('react-dev-utils/printBuildError'); 28 | 29 | const measureFileSizesBeforeBuild = 30 | FileSizeReporter.measureFileSizesBeforeBuild; 31 | const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; 32 | const useYarn = fs.existsSync(paths.yarnLockFile); 33 | 34 | // These sizes are pretty large. We'll warn for bundles exceeding them. 35 | const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; 36 | const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; 37 | 38 | // Warn and crash if required files are missing 39 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 40 | process.exit(1); 41 | } 42 | 43 | // First, read the current file sizes in build directory. 44 | // This lets us display how much they changed later. 45 | measureFileSizesBeforeBuild(paths.appBuild) 46 | .then(previousFileSizes => { 47 | // Remove all content but keep the directory so that 48 | // if you're in it, you don't end up in Trash 49 | fs.emptyDirSync(paths.appBuild); 50 | // Merge with the public folder 51 | copyPublicFolder(); 52 | // Start the webpack build 53 | return build(previousFileSizes); 54 | }) 55 | .then( 56 | ({ stats, previousFileSizes, warnings }) => { 57 | if (warnings.length) { 58 | console.log(chalk.yellow('Compiled with warnings.\n')); 59 | console.log(warnings.join('\n\n')); 60 | console.log( 61 | '\nSearch for the ' + 62 | chalk.underline(chalk.yellow('keywords')) + 63 | ' to learn more about each warning.' 64 | ); 65 | console.log( 66 | 'To ignore, add ' + 67 | chalk.cyan('// eslint-disable-next-line') + 68 | ' to the line before.\n' 69 | ); 70 | } else { 71 | console.log(chalk.green('Compiled successfully.\n')); 72 | } 73 | 74 | console.log('File sizes after gzip:\n'); 75 | printFileSizesAfterBuild( 76 | stats, 77 | previousFileSizes, 78 | paths.appBuild, 79 | WARN_AFTER_BUNDLE_GZIP_SIZE, 80 | WARN_AFTER_CHUNK_GZIP_SIZE 81 | ); 82 | console.log(); 83 | 84 | const appPackage = require(paths.appPackageJson); 85 | const publicUrl = paths.publicUrl; 86 | const publicPath = config.output.publicPath; 87 | const buildFolder = path.relative(process.cwd(), paths.appBuild); 88 | printHostingInstructions( 89 | appPackage, 90 | publicUrl, 91 | publicPath, 92 | buildFolder, 93 | useYarn 94 | ); 95 | 96 | process.exit(); 97 | }, 98 | err => { 99 | console.log(chalk.red('Failed to compile.\n')); 100 | printBuildError(err); 101 | process.exit(1); 102 | } 103 | ); 104 | 105 | // Create the production build and print the deployment instructions. 106 | function build(previousFileSizes) { 107 | console.log('Creating an optimized production build...'); 108 | 109 | let compiler = webpack(config); 110 | return new Promise((resolve, reject) => { 111 | compiler.run((err, stats) => { 112 | if (err) { 113 | return reject(err); 114 | } 115 | const messages = formatWebpackMessages(stats.toJson({}, true)); 116 | if (messages.errors.length) { 117 | // Only keep the first error. Others are often indicative 118 | // of the same problem, but confuse the reader with noise. 119 | if (messages.errors.length > 1) { 120 | messages.errors.length = 1; 121 | } 122 | return reject(new Error(messages.errors.join('\n\n'))); 123 | } 124 | if ( 125 | process.env.CI && 126 | (typeof process.env.CI !== 'string' || 127 | process.env.CI.toLowerCase() !== 'false') && 128 | messages.warnings.length 129 | ) { 130 | console.log( 131 | chalk.yellow( 132 | '\nTreating warnings as errors because process.env.CI = true.\n' + 133 | 'Most CI servers set it automatically.\n' 134 | ) 135 | ); 136 | return reject(new Error(messages.warnings.join('\n\n'))); 137 | } 138 | return resolve({ 139 | stats, 140 | previousFileSizes, 141 | warnings: messages.warnings, 142 | }); 143 | }); 144 | }); 145 | } 146 | 147 | function copyPublicFolder() { 148 | fs.copySync(paths.appPublic, paths.appBuild, { 149 | dereference: true, 150 | filter: file => file !== paths.appHtml, 151 | }); 152 | } 153 | -------------------------------------------------------------------------------- /config/webpack.config.dev.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const webpack = require('webpack'); 5 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 6 | const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); 7 | const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); 8 | const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); 9 | const eslintFormatter = require('react-dev-utils/eslintFormatter'); 10 | const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); 11 | const getClientEnvironment = require('./env'); 12 | const paths = require('./paths'); 13 | const getCustomConfig = require('./custom-react-scripts/config'); 14 | 15 | // Webpack uses `publicPath` to determine where the app is being served from. 16 | // In development, we always serve from the root. This makes config easier. 17 | const publicPath = '/'; 18 | // `publicUrl` is just like `publicPath`, but we will provide it to our app 19 | // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. 20 | // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. 21 | const publicUrl = ''; 22 | // Get environment variables to inject into our app. 23 | const env = getClientEnvironment(publicUrl); 24 | //Get custom configuration for injecting plugins, presets and loaders 25 | const customConfig = getCustomConfig(true); 26 | 27 | // This is the development configuration. 28 | // It is focused on developer experience and fast rebuilds. 29 | // The production configuration is different and lives in a separate file. 30 | module.exports = { 31 | // You may want 'eval' instead if you prefer to see the compiled output in DevTools. 32 | // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343. 33 | devtool: 'cheap-module-source-map', 34 | // These are the "entry points" to our application. 35 | // This means they will be the "root" imports that are included in JS bundle. 36 | // The first two entry points enable "hot" CSS and auto-refreshes for JS. 37 | entry: [ 38 | // Include an alternative client for WebpackDevServer. A client's job is to 39 | // connect to WebpackDevServer by a socket and get notified about changes. 40 | // When you save a file, the client will either apply hot updates (in case 41 | // of CSS changes), or refresh the page (in case of JS changes). When you 42 | // make a syntax error, this client will display a syntax error overlay. 43 | // Note: instead of the default WebpackDevServer client, we use a custom one 44 | // to bring better experience for Create React App users. You can replace 45 | // the line below with these two lines if you prefer the stock client: 46 | // require.resolve('webpack-dev-server/client') + '?/', 47 | // require.resolve('webpack/hot/dev-server'), 48 | require.resolve('react-dev-utils/webpackHotDevClient'), 49 | // We ship a few polyfills by default: 50 | require.resolve('./polyfills'), 51 | // Errors should be considered fatal in development 52 | require.resolve('react-error-overlay'), 53 | // Finally, this is your app's code: 54 | paths.appIndexJs, 55 | // We include the app code last so that if there is a runtime error during 56 | // initialization, it doesn't blow up the WebpackDevServer client, and 57 | // changing JS code would still trigger a refresh. 58 | ], 59 | output: { 60 | // Next line is not used in dev but WebpackDevServer crashes without it: 61 | path: paths.appBuild, 62 | // Add /* filename */ comments to generated require()s in the output. 63 | pathinfo: true, 64 | // This does not produce a real file. It's just the virtual path that is 65 | // served by WebpackDevServer in development. This is the JS bundle 66 | // containing code from all our entry points, and the Webpack runtime. 67 | filename: 'static/js/bundle.js', 68 | // There are also additional JS chunk files if you use code splitting. 69 | chunkFilename: 'static/js/[name].chunk.js', 70 | // This is the URL that app is served from. We use "/" in development. 71 | publicPath: publicPath, 72 | // Point sourcemap entries to original disk location (format as URL on Windows) 73 | devtoolModuleFilenameTemplate: info => 74 | path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'), 75 | }, 76 | resolve: { 77 | // This allows you to set a fallback for where Webpack should look for modules. 78 | // We placed these paths second because we want `node_modules` to "win" 79 | // if there are any conflicts. This matches Node resolution mechanism. 80 | // https://github.com/facebookincubator/create-react-app/issues/253 81 | modules: ['node_modules', paths.appNodeModules].concat( 82 | // It is guaranteed to exist because we tweak it in `env.js` 83 | process.env.NODE_PATH.split(path.delimiter).filter(Boolean) 84 | ), 85 | // These are the reasonable defaults supported by the Node ecosystem. 86 | // We also include JSX as a common component filename extension to support 87 | // some tools, although we do not recommend using it, see: 88 | // https://github.com/facebookincubator/create-react-app/issues/290 89 | // `web` extension prefixes have been added for better support 90 | // for React Native Web. 91 | extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'], 92 | alias: { 93 | 94 | // Support React Native Web 95 | // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 96 | 'react-native': 'react-native-web', 97 | }, 98 | plugins: [ 99 | // Prevents users from importing files from outside of src/ (or node_modules/). 100 | // This often causes confusion because we only process files within src/ with babel. 101 | // To fix this, we prevent you from importing files out of src/ -- if you'd like to, 102 | // please link the files into your node_modules/ and let module-resolution kick in. 103 | // Make sure your source files are compiled, as they will not be processed in any way. 104 | new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]), 105 | ], 106 | }, 107 | module: { 108 | strictExportPresence: true, 109 | rules: [ 110 | // TODO: Disable require.ensure as it's not a standard language feature. 111 | // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176. 112 | // { parser: { requireEnsure: false } }, 113 | 114 | // First, run the linter. 115 | // It's important to do this before Babel processes the JS. 116 | { 117 | test: /\.(js|jsx)$/, 118 | enforce: 'pre', 119 | use: [ 120 | { 121 | options: { 122 | formatter: eslintFormatter, 123 | eslintPath: require.resolve('eslint'), 124 | 125 | }, 126 | loader: require.resolve('eslint-loader'), 127 | }, 128 | ], 129 | include: paths.appSrc, 130 | }, 131 | { 132 | // "oneOf" will traverse all following loaders until one will 133 | // match the requirements. When no loader matches it will fall 134 | // back to the "file" loader at the end of the loader list. 135 | oneOf: [ 136 | // "url" loader works like "file" loader except that it embeds assets 137 | // smaller than specified limit in bytes as data URLs to avoid requests. 138 | // A missing `test` is equivalent to a match. 139 | { 140 | test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], 141 | loader: require.resolve('url-loader'), 142 | options: { 143 | limit: 10000, 144 | name: 'static/media/[name].[hash:8].[ext]', 145 | }, 146 | }, 147 | // Process JS with Babel. 148 | { 149 | test: /\.(js|jsx)$/, 150 | include: paths.appSrc, 151 | loader: require.resolve('babel-loader'), 152 | options: { 153 | babelrc: false, 154 | presets: [require.resolve('babel-preset-react-app')].concat( 155 | customConfig.babelPresets 156 | ), 157 | plugins: customConfig.babelPlugins, 158 | // This is a feature of `babel-loader` for webpack (not Babel itself). 159 | // It enables caching results in ./node_modules/.cache/babel-loader/ 160 | // directory for faster rebuilds. 161 | cacheDirectory: true, 162 | }, 163 | }, 164 | ...customConfig.webpackLoaders, 165 | // "file" loader makes sure those assets get served by WebpackDevServer. 166 | // When you `import` an asset, you get its (virtual) filename. 167 | // In production, they would get copied to the `build` folder. 168 | // This loader don't uses a "test" so it will catch all modules 169 | // that fall through the other loaders. 170 | { 171 | // Exclude `js` files to keep "css" loader working as it injects 172 | // it's runtime that would otherwise processed through "file" loader. 173 | // Also exclude `html` and `json` extensions so they get processed 174 | // by webpacks internal loaders. 175 | exclude: [/\.js$/, /\.html$/, /\.json$/], 176 | loader: require.resolve('file-loader'), 177 | options: { 178 | name: 'static/media/[name].[hash:8].[ext]', 179 | }, 180 | }, 181 | ], 182 | }, 183 | // ** STOP ** Are you adding a new loader? 184 | // Make sure to add the new loader(s) before the "file" loader. 185 | ], 186 | }, 187 | plugins: [ 188 | // Makes some environment variables available in index.html. 189 | // The public URL is available as %PUBLIC_URL% in index.html, e.g.: 190 | // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 191 | // In development, this will be an empty string. 192 | new InterpolateHtmlPlugin(env.raw), 193 | // Generates an `index.html` file with the <script> injected. 194 | new HtmlWebpackPlugin({ 195 | inject: true, 196 | template: paths.appHtml, 197 | }), 198 | // Add module names to factory functions so they appear in browser profiler. 199 | new webpack.NamedModulesPlugin(), 200 | // Makes some environment variables available to the JS code, for example: 201 | // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`. 202 | new webpack.DefinePlugin(env.stringified), 203 | // This is necessary to emit hot updates (currently CSS only): 204 | new webpack.HotModuleReplacementPlugin(), 205 | // Watcher doesn't work well if you mistype casing in a path so we use 206 | // a plugin that prints an error when you attempt to do this. 207 | // See https://github.com/facebookincubator/create-react-app/issues/240 208 | new CaseSensitivePathsPlugin(), 209 | // If you require a missing module and then `npm install` it, you still have 210 | // to restart the development server for Webpack to discover it. This plugin 211 | // makes the discovery automatic so you don't have to restart. 212 | // See https://github.com/facebookincubator/create-react-app/issues/186 213 | new WatchMissingNodeModulesPlugin(paths.appNodeModules), 214 | // Moment.js is an extremely popular library that bundles large locale files 215 | // by default due to how Webpack interprets its code. This is a practical 216 | // solution that requires the user to opt into importing specific locales. 217 | // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack 218 | // You can remove this if you don't use Moment.js: 219 | new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), 220 | ...customConfig.webpackPlugins, 221 | ], 222 | // Some libraries import Node modules but don't use them in the browser. 223 | // Tell Webpack to provide empty mocks for them so importing them works. 224 | node: { 225 | dgram: 'empty', 226 | fs: 'empty', 227 | net: 'empty', 228 | tls: 'empty', 229 | }, 230 | // Turn off performance hints during development because we don't do any 231 | // splitting or minification in interest of speed. These warnings become 232 | // cumbersome. 233 | performance: { 234 | hints: false, 235 | }, 236 | }; 237 | -------------------------------------------------------------------------------- /config/webpack.config.prod.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const webpack = require('webpack'); 5 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 6 | const ExtractTextPlugin = require('extract-text-webpack-plugin'); 7 | const ManifestPlugin = require('webpack-manifest-plugin'); 8 | const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); 9 | const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); 10 | const eslintFormatter = require('react-dev-utils/eslintFormatter'); 11 | const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); 12 | const paths = require('./paths'); 13 | const getClientEnvironment = require('./env'); 14 | const getCustomConfig = require('./custom-react-scripts/config'); 15 | 16 | // Webpack uses `publicPath` to determine where the app is being served from. 17 | // It requires a trailing slash, or the file assets will get an incorrect path. 18 | const publicPath = paths.servedPath; 19 | // Source maps are resource heavy and can cause out of memory issue for large source files. 20 | const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; 21 | // `publicUrl` is just like `publicPath`, but we will provide it to our app 22 | // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. 23 | // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. 24 | const publicUrl = publicPath.slice(0, -1); 25 | // Get environment variables to inject into our app. 26 | const env = getClientEnvironment(publicUrl); 27 | //Get custom configuration for injecting plugins, presets and loaders 28 | const customConfig = getCustomConfig(false); 29 | 30 | // Assert this just to be safe. 31 | // Development builds of React are slow and not intended for production. 32 | if (env.stringified['process.env'].NODE_ENV !== '"production"') { 33 | throw new Error('Production builds must have NODE_ENV=production.'); 34 | } 35 | 36 | // Note: defined here because it will be used more than once. 37 | const cssFilename = 'static/css/[name].[contenthash:8].css'; 38 | 39 | // This is the production configuration. 40 | // It compiles slowly and is focused on producing a fast and minimal bundle. 41 | // The development configuration is different and lives in a separate file. 42 | module.exports = { 43 | // Don't attempt to continue if there are any errors. 44 | bail: true, 45 | // We generate sourcemaps in production. This is slow but gives good results. 46 | // You can exclude the *.map files from the build during deployment. 47 | devtool: shouldUseSourceMap ? 'source-map' : false, 48 | // In production, we only want to load the polyfills and the app code. 49 | entry: [require.resolve('./polyfills'), paths.appIndexJs], 50 | output: { 51 | // The build folder. 52 | path: paths.appBuild, 53 | // Generated JS file names (with nested folders). 54 | // There will be one main bundle, and one file per asynchronous chunk. 55 | // We don't currently advertise code splitting but Webpack supports it. 56 | filename: 'static/js/[name].[chunkhash:8].js', 57 | chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', 58 | // We inferred the "public path" (such as / or /my-project) from homepage. 59 | publicPath: publicPath, 60 | // Point sourcemap entries to original disk location (format as URL on Windows) 61 | devtoolModuleFilenameTemplate: info => 62 | path 63 | .relative(paths.appSrc, info.absoluteResourcePath) 64 | .replace(/\\/g, '/'), 65 | }, 66 | resolve: { 67 | // This allows you to set a fallback for where Webpack should look for modules. 68 | // We placed these paths second because we want `node_modules` to "win" 69 | // if there are any conflicts. This matches Node resolution mechanism. 70 | // https://github.com/facebookincubator/create-react-app/issues/253 71 | modules: ['node_modules', paths.appNodeModules].concat( 72 | // It is guaranteed to exist because we tweak it in `env.js` 73 | process.env.NODE_PATH.split(path.delimiter).filter(Boolean) 74 | ), 75 | // These are the reasonable defaults supported by the Node ecosystem. 76 | // We also include JSX as a common component filename extension to support 77 | // some tools, although we do not recommend using it, see: 78 | // https://github.com/facebookincubator/create-react-app/issues/290 79 | // `web` extension prefixes have been added for better support 80 | // for React Native Web. 81 | extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'], 82 | alias: { 83 | 84 | // Support React Native Web 85 | // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 86 | 'react-native': 'react-native-web', 87 | }, 88 | plugins: [ 89 | // Prevents users from importing files from outside of src/ (or node_modules/). 90 | // This often causes confusion because we only process files within src/ with babel. 91 | // To fix this, we prevent you from importing files out of src/ -- if you'd like to, 92 | // please link the files into your node_modules/ and let module-resolution kick in. 93 | // Make sure your source files are compiled, as they will not be processed in any way. 94 | new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]), 95 | ], 96 | }, 97 | module: { 98 | strictExportPresence: true, 99 | rules: [ 100 | // TODO: Disable require.ensure as it's not a standard language feature. 101 | // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176. 102 | // { parser: { requireEnsure: false } }, 103 | 104 | // First, run the linter. 105 | // It's important to do this before Babel processes the JS. 106 | { 107 | test: /\.(js|jsx)$/, 108 | enforce: 'pre', 109 | use: [ 110 | { 111 | options: { 112 | formatter: eslintFormatter, 113 | eslintPath: require.resolve('eslint'), 114 | 115 | }, 116 | loader: require.resolve('eslint-loader'), 117 | }, 118 | ], 119 | include: paths.appSrc, 120 | }, 121 | { 122 | // "oneOf" will traverse all following loaders until one will 123 | // match the requirements. When no loader matches it will fall 124 | // back to the "file" loader at the end of the loader list. 125 | oneOf: [ 126 | // "url" loader works just like "file" loader but it also embeds 127 | // assets smaller than specified size as data URLs to avoid requests. 128 | { 129 | test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], 130 | loader: require.resolve('url-loader'), 131 | options: { 132 | limit: 10000, 133 | name: 'static/media/[name].[hash:8].[ext]', 134 | }, 135 | }, 136 | // Process JS with Babel. 137 | { 138 | test: /\.(js|jsx)$/, 139 | include: paths.appSrc, 140 | loader: require.resolve('babel-loader'), 141 | options: { 142 | babelrc: false, 143 | presets: [require.resolve('babel-preset-react-app')].concat( 144 | customConfig.babelPresets 145 | ), 146 | plugins: customConfig.babelPlugins, 147 | compact: true, 148 | }, 149 | }, 150 | ...customConfig.webpackLoaders, 151 | // "file" loader makes sure assets end up in the `build` folder. 152 | // When you `import` an asset, you get its filename. 153 | // This loader don't uses a "test" so it will catch all modules 154 | // that fall through the other loaders. 155 | { 156 | loader: require.resolve('file-loader'), 157 | // Exclude `js` files to keep "css" loader working as it injects 158 | // it's runtime that would otherwise processed through "file" loader. 159 | // Also exclude `html` and `json` extensions so they get processed 160 | // by webpacks internal loaders. 161 | exclude: [/\.js$/, /\.html$/, /\.json$/], 162 | options: { 163 | name: 'static/media/[name].[hash:8].[ext]', 164 | }, 165 | }, 166 | // ** STOP ** Are you adding a new loader? 167 | // Make sure to add the new loader(s) before the "file" loader. 168 | ], 169 | }, 170 | ], 171 | }, 172 | plugins: [ 173 | // Makes some environment variables available in index.html. 174 | // The public URL is available as %PUBLIC_URL% in index.html, e.g.: 175 | // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 176 | // In production, it will be an empty string unless you specify "homepage" 177 | // in `package.json`, in which case it will be the pathname of that URL. 178 | new InterpolateHtmlPlugin(env.raw), 179 | // Generates an `index.html` file with the <script> injected. 180 | new HtmlWebpackPlugin({ 181 | inject: true, 182 | template: paths.appHtml, 183 | minify: { 184 | removeComments: true, 185 | collapseWhitespace: true, 186 | removeRedundantAttributes: true, 187 | useShortDoctype: true, 188 | removeEmptyAttributes: true, 189 | removeStyleLinkTypeAttributes: true, 190 | keepClosingSlash: true, 191 | minifyJS: true, 192 | minifyCSS: true, 193 | minifyURLs: true, 194 | }, 195 | }), 196 | // Makes some environment variables available to the JS code, for example: 197 | // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`. 198 | // It is absolutely essential that NODE_ENV was set to production here. 199 | // Otherwise React will be compiled in the very slow development mode. 200 | new webpack.DefinePlugin(env.stringified), 201 | // Minify the code. 202 | new webpack.optimize.UglifyJsPlugin({ 203 | compress: { 204 | warnings: false, 205 | // Disabled because of an issue with Uglify breaking seemingly valid code: 206 | // https://github.com/facebookincubator/create-react-app/issues/2376 207 | // Pending further investigation: 208 | // https://github.com/mishoo/UglifyJS2/issues/2011 209 | comparisons: false, 210 | }, 211 | output: { 212 | comments: false, 213 | // Turned on because emoji and regex is not minified properly using default 214 | // https://github.com/facebookincubator/create-react-app/issues/2488 215 | ascii_only: true, 216 | }, 217 | sourceMap: shouldUseSourceMap, 218 | }), 219 | // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`. 220 | new ExtractTextPlugin({ 221 | filename: cssFilename, 222 | }), 223 | // Generate a manifest file which contains a mapping of all asset filenames 224 | // to their corresponding output file so that tools can pick it up without 225 | // having to parse `index.html`. 226 | new ManifestPlugin({ 227 | fileName: 'asset-manifest.json', 228 | }), 229 | // Generate a service worker script that will precache, and keep up to date, 230 | // the HTML & assets that are part of the Webpack build. 231 | new SWPrecacheWebpackPlugin({ 232 | // By default, a cache-busting query parameter is appended to requests 233 | // used to populate the caches, to ensure the responses are fresh. 234 | // If a URL is already hashed by Webpack, then there is no concern 235 | // about it being stale, and the cache-busting can be skipped. 236 | dontCacheBustUrlsMatching: /\.\w{8}\./, 237 | filename: 'service-worker.js', 238 | logger(message) { 239 | if (message.indexOf('Total precache size is') === 0) { 240 | // This message occurs for every build and is a bit too noisy. 241 | return; 242 | } 243 | if (message.indexOf('Skipping static resource') === 0) { 244 | // This message obscures real errors so we ignore it. 245 | // https://github.com/facebookincubator/create-react-app/issues/2612 246 | return; 247 | } 248 | console.log(message); 249 | }, 250 | minify: true, 251 | // For unknown URLs, fallback to the index page 252 | navigateFallback: publicUrl + '/index.html', 253 | // Ignores URLs starting from /__ (useful for Firebase): 254 | // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219 255 | navigateFallbackWhitelist: [/^(?!\/__).*/], 256 | // Don't precache sourcemaps (they're large) and build asset manifest: 257 | staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/], 258 | }), 259 | // Moment.js is an extremely popular library that bundles large locale files 260 | // by default due to how Webpack interprets its code. This is a practical 261 | // solution that requires the user to opt into importing specific locales. 262 | // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack 263 | // You can remove this if you don't use Moment.js: 264 | new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), 265 | ], 266 | // Some libraries import Node modules but don't use them in the browser. 267 | // Tell Webpack to provide empty mocks for them so importing them works. 268 | node: { 269 | dgram: 'empty', 270 | fs: 'empty', 271 | net: 'empty', 272 | tls: 'empty', 273 | }, 274 | }; 275 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Course 2 | 3 | This project was built to teach the [Advanced State Management in React (feat. Redux and MobX) Course](https://frontendmasters.com/courses/react-state/) for Frontend Masters. 4 | 5 | ## Code 6 | 7 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 8 | 9 | Below you will find some information on how to perform common tasks.<br> 10 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 11 | 12 | ## Table of Contents 13 | 14 | - [Updating to New Releases](#updating-to-new-releases) 15 | - [Sending Feedback](#sending-feedback) 16 | - [Folder Structure](#folder-structure) 17 | - [Available Scripts](#available-scripts) 18 | - [npm start](#npm-start) 19 | - [npm test](#npm-test) 20 | - [npm run build](#npm-run-build) 21 | - [npm run eject](#npm-run-eject) 22 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 23 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 24 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 25 | - [Debugging in the Editor](#debugging-in-the-editor) 26 | - [Formatting Code Automatically](#formatting-code-automatically) 27 | - [Changing the Page `<title>`](#changing-the-page-title) 28 | - [Installing a Dependency](#installing-a-dependency) 29 | - [Importing a Component](#importing-a-component) 30 | - [Code Splitting](#code-splitting) 31 | - [Adding a Stylesheet](#adding-a-stylesheet) 32 | - [Post-Processing CSS](#post-processing-css) 33 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) 34 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) 35 | - [Using the `public` Folder](#using-the-public-folder) 36 | - [Changing the HTML](#changing-the-html) 37 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 38 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 39 | - [Using Global Variables](#using-global-variables) 40 | - [Adding Bootstrap](#adding-bootstrap) 41 | - [Using a Custom Theme](#using-a-custom-theme) 42 | - [Adding Flow](#adding-flow) 43 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 44 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 45 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 46 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 47 | - [Can I Use Decorators?](#can-i-use-decorators) 48 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 49 | - [Node](#node) 50 | - [Ruby on Rails](#ruby-on-rails) 51 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 52 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) 53 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 54 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy) 55 | - [Using HTTPS in Development](#using-https-in-development) 56 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 57 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 58 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 59 | - [Running Tests](#running-tests) 60 | - [Filename Conventions](#filename-conventions) 61 | - [Command Line Interface](#command-line-interface) 62 | - [Version Control Integration](#version-control-integration) 63 | - [Writing Tests](#writing-tests) 64 | - [Testing Components](#testing-components) 65 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 66 | - [Initializing Test Environment](#initializing-test-environment) 67 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 68 | - [Coverage Reporting](#coverage-reporting) 69 | - [Continuous Integration](#continuous-integration) 70 | - [Disabling jsdom](#disabling-jsdom) 71 | - [Snapshot Testing](#snapshot-testing) 72 | - [Editor Integration](#editor-integration) 73 | - [Developing Components in Isolation](#developing-components-in-isolation) 74 | - [Getting Started with Storybook](#getting-started-with-storybook) 75 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 76 | - [Making a Progressive Web App](#making-a-progressive-web-app) 77 | - [Opting Out of Caching](#opting-out-of-caching) 78 | - [Offline-First Considerations](#offline-first-considerations) 79 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 80 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 81 | - [Deployment](#deployment) 82 | - [Static Server](#static-server) 83 | - [Other Solutions](#other-solutions) 84 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 85 | - [Building for Relative Paths](#building-for-relative-paths) 86 | - [Azure](#azure) 87 | - [Firebase](#firebase) 88 | - [GitHub Pages](#github-pages) 89 | - [Heroku](#heroku) 90 | - [Modulus](#modulus) 91 | - [Netlify](#netlify) 92 | - [Now](#now) 93 | - [S3 and CloudFront](#s3-and-cloudfront) 94 | - [Surge](#surge) 95 | - [Advanced Configuration](#advanced-configuration) 96 | - [Troubleshooting](#troubleshooting) 97 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 98 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 99 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 100 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 101 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) 102 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 103 | - [Something Missing?](#something-missing) 104 | 105 | ## Updating to New Releases 106 | 107 | Create React App is divided into two packages: 108 | 109 | * `create-react-app` is a global command-line utility that you use to create new projects. 110 | * `react-scripts` is a development dependency in the generated projects (including this one). 111 | 112 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 113 | 114 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 115 | 116 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 117 | 118 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 119 | 120 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 121 | 122 | ## Sending Feedback 123 | 124 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 125 | 126 | ## Folder Structure 127 | 128 | After creation, your project should look like this: 129 | 130 | ``` 131 | my-app/ 132 | README.md 133 | node_modules/ 134 | package.json 135 | public/ 136 | index.html 137 | favicon.ico 138 | src/ 139 | App.css 140 | App.js 141 | App.test.js 142 | index.css 143 | index.js 144 | logo.svg 145 | ``` 146 | 147 | For the project to build, **these files must exist with exact filenames**: 148 | 149 | * `public/index.html` is the page template; 150 | * `src/index.js` is the JavaScript entry point. 151 | 152 | You can delete or rename the other files. 153 | 154 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 155 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 156 | 157 | Only files inside `public` can be used from `public/index.html`.<br> 158 | Read instructions below for using assets from JavaScript and HTML. 159 | 160 | You can, however, create more top-level directories.<br> 161 | They will not be included in the production build so you can use them for things like documentation. 162 | 163 | ## Available Scripts 164 | 165 | In the project directory, you can run: 166 | 167 | ### `npm start` 168 | 169 | Runs the app in the development mode.<br> 170 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 171 | 172 | The page will reload if you make edits.<br> 173 | You will also see any lint errors in the console. 174 | 175 | ### `npm test` 176 | 177 | Launches the test runner in the interactive watch mode.<br> 178 | See the section about [running tests](#running-tests) for more information. 179 | 180 | ### `npm run build` 181 | 182 | Builds the app for production to the `build` folder.<br> 183 | It correctly bundles React in production mode and optimizes the build for the best performance. 184 | 185 | The build is minified and the filenames include the hashes.<br> 186 | Your app is ready to be deployed! 187 | 188 | See the section about [deployment](#deployment) for more information. 189 | 190 | ### `npm run eject` 191 | 192 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 193 | 194 | 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. 195 | 196 | 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. 197 | 198 | 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. 199 | 200 | ## Supported Language Features and Polyfills 201 | 202 | This project supports a superset of the latest JavaScript standard.<br> 203 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 204 | 205 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 206 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 207 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 208 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 209 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). 210 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 211 | 212 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 213 | 214 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. 215 | 216 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 217 | 218 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 219 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 220 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 221 | 222 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. 223 | 224 | ## Syntax Highlighting in the Editor 225 | 226 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. 227 | 228 | ## Displaying Lint Output in the Editor 229 | 230 | >Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 231 | >It also only works with npm 3 or higher. 232 | 233 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 234 | 235 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 236 | 237 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 238 | 239 | ```js 240 | { 241 | "extends": "react-app" 242 | } 243 | ``` 244 | 245 | Now your editor should report the linting warnings. 246 | 247 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. 248 | 249 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 250 | 251 | ## Debugging in the Editor 252 | 253 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.** 254 | 255 | Visual Studio Code supports debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. 256 | 257 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. 258 | 259 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 260 | 261 | ```json 262 | { 263 | "version": "0.2.0", 264 | "configurations": [{ 265 | "name": "Chrome", 266 | "type": "chrome", 267 | "request": "launch", 268 | "url": "http://localhost:3000", 269 | "webRoot": "${workspaceRoot}/src", 270 | "userDataDir": "${workspaceRoot}/.vscode/chrome", 271 | "sourceMapPathOverrides": { 272 | "webpack:///src/*": "${webRoot}/*" 273 | } 274 | }] 275 | } 276 | ``` 277 | 278 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. 279 | 280 | ## Formatting Code Automatically 281 | 282 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/). 283 | 284 | To format our code whenever we make a commit in git, we need to install the following dependencies: 285 | 286 | ```sh 287 | npm install --save husky lint-staged prettier 288 | ``` 289 | 290 | Alternatively you may use `yarn`: 291 | 292 | ```sh 293 | yarn add husky lint-staged prettier 294 | ``` 295 | 296 | * `husky` makes it easy to use githooks as if they are npm scripts. 297 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). 298 | * `prettier` is the JavaScript formatter we will run before commits. 299 | 300 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 301 | 302 | Add the following line to `scripts` section: 303 | 304 | ```diff 305 | "scripts": { 306 | + "precommit": "lint-staged", 307 | "start": "react-scripts start", 308 | "build": "react-scripts build", 309 | ``` 310 | 311 | Next we add a 'lint-staged' field to the `package.json`, for example: 312 | 313 | ```diff 314 | "dependencies": { 315 | // ... 316 | }, 317 | + "lint-staged": { 318 | + "src/**/*.{js,jsx,json,css}": [ 319 | + "prettier --single-quote --write", 320 | + "git add" 321 | + ] 322 | + }, 323 | "scripts": { 324 | ``` 325 | 326 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time. 327 | 328 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page. 329 | 330 | ## Changing the Page `<title>` 331 | 332 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 333 | 334 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. 335 | 336 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. 337 | 338 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). 339 | 340 | ## Installing a Dependency 341 | 342 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: 343 | 344 | ```sh 345 | npm install --save react-router 346 | ``` 347 | 348 | Alternatively you may use `yarn`: 349 | 350 | ```sh 351 | yarn add react-router 352 | ``` 353 | 354 | This works for any library, not just `react-router`. 355 | 356 | ## Importing a Component 357 | 358 | This project setup supports ES6 modules thanks to Babel.<br> 359 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. 360 | 361 | For example: 362 | 363 | ### `Button.js` 364 | 365 | ```js 366 | import React, { Component } from 'react'; 367 | 368 | class Button extends Component { 369 | render() { 370 | // ... 371 | } 372 | } 373 | 374 | export default Button; // Don’t forget to use export default! 375 | ``` 376 | 377 | ### `DangerButton.js` 378 | 379 | 380 | ```js 381 | import React, { Component } from 'react'; 382 | import Button from './Button'; // Import a component from another file 383 | 384 | class DangerButton extends Component { 385 | render() { 386 | return <Button color="red" />; 387 | } 388 | } 389 | 390 | export default DangerButton; 391 | ``` 392 | 393 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. 394 | 395 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. 396 | 397 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. 398 | 399 | Learn more about ES6 modules: 400 | 401 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) 402 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 403 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 404 | 405 | ## Code Splitting 406 | 407 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. 408 | 409 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. 410 | 411 | Here is an example: 412 | 413 | ### `moduleA.js` 414 | 415 | ```js 416 | const moduleA = 'Hello'; 417 | 418 | export { moduleA }; 419 | ``` 420 | ### `App.js` 421 | 422 | ```js 423 | import React, { Component } from 'react'; 424 | 425 | class App extends Component { 426 | handleClick = () => { 427 | import('./moduleA') 428 | .then(({ moduleA }) => { 429 | // Use moduleA 430 | }) 431 | .catch(err => { 432 | // Handle failure 433 | }); 434 | }; 435 | 436 | render() { 437 | return ( 438 | <div> 439 | <button onClick={this.handleClick}>Load</button> 440 | </div> 441 | ); 442 | } 443 | } 444 | 445 | export default App; 446 | ``` 447 | 448 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 449 | 450 | You can also use it with `async` / `await` syntax if you prefer it. 451 | 452 | ### With React Router 453 | 454 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app). 455 | 456 | ## Adding a Stylesheet 457 | 458 | This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: 459 | 460 | ### `Button.css` 461 | 462 | ```css 463 | .Button { 464 | padding: 20px; 465 | } 466 | ``` 467 | 468 | ### `Button.js` 469 | 470 | ```js 471 | import React, { Component } from 'react'; 472 | import './Button.css'; // Tell Webpack that Button.js uses these styles 473 | 474 | class Button extends Component { 475 | render() { 476 | // You can use them as regular CSS styles 477 | return <div className="Button" />; 478 | } 479 | } 480 | ``` 481 | 482 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 483 | 484 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. 485 | 486 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. 487 | 488 | ## Post-Processing CSS 489 | 490 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. 491 | 492 | For example, this: 493 | 494 | ```css 495 | .App { 496 | display: flex; 497 | flex-direction: row; 498 | align-items: center; 499 | } 500 | ``` 501 | 502 | becomes this: 503 | 504 | ```css 505 | .App { 506 | display: -webkit-box; 507 | display: -ms-flexbox; 508 | display: flex; 509 | -webkit-box-orient: horizontal; 510 | -webkit-box-direction: normal; 511 | -ms-flex-direction: row; 512 | flex-direction: row; 513 | -webkit-box-align: center; 514 | -ms-flex-align: center; 515 | align-items: center; 516 | } 517 | ``` 518 | 519 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 520 | 521 | ## Adding a CSS Preprocessor (Sass, Less etc.) 522 | 523 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 524 | 525 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. 526 | 527 | First, let’s install the command-line interface for Sass: 528 | 529 | ```sh 530 | npm install --save node-sass-chokidar 531 | ``` 532 | 533 | Alternatively you may use `yarn`: 534 | 535 | ```sh 536 | yarn add node-sass-chokidar 537 | ``` 538 | 539 | Then in `package.json`, add the following lines to `scripts`: 540 | 541 | ```diff 542 | "scripts": { 543 | + "build-css": "node-sass-chokidar src/ -o src/", 544 | + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 545 | "start": "react-scripts start", 546 | "build": "react-scripts build", 547 | "test": "react-scripts test --env=jsdom", 548 | ``` 549 | 550 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. 551 | 552 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. 553 | 554 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 555 | 556 | To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. 557 | 558 | ``` 559 | "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", 560 | "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", 561 | ``` 562 | 563 | This will allow you to do imports like 564 | 565 | ```scss 566 | @import 'styles/_colors.scss'; // assuming a styles directory under src/ 567 | @import 'nprogress/nprogress'; // importing a css file from the nprogress node module 568 | ``` 569 | 570 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. 571 | 572 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: 573 | 574 | ```sh 575 | npm install --save npm-run-all 576 | ``` 577 | 578 | Alternatively you may use `yarn`: 579 | 580 | ```sh 581 | yarn add npm-run-all 582 | ``` 583 | 584 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands: 585 | 586 | ```diff 587 | "scripts": { 588 | "build-css": "node-sass-chokidar src/ -o src/", 589 | "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 590 | - "start": "react-scripts start", 591 | - "build": "react-scripts build", 592 | + "start-js": "react-scripts start", 593 | + "start": "npm-run-all -p watch-css start-js", 594 | + "build": "npm run build-css && react-scripts build", 595 | "test": "react-scripts test --env=jsdom", 596 | "eject": "react-scripts eject" 597 | } 598 | ``` 599 | 600 | Now running `npm start` and `npm run build` also builds Sass files. 601 | 602 | **Why `node-sass-chokidar`?** 603 | 604 | `node-sass` has been reported as having the following issues: 605 | 606 | - `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker. 607 | 608 | - Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) 609 | 610 | - `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) 611 | 612 | `node-sass-chokidar` is used here as it addresses these issues. 613 | 614 | ## Adding Images, Fonts, and Files 615 | 616 | With Webpack, using static assets like images and fonts works similarly to CSS. 617 | 618 | You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. 619 | 620 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153). 621 | 622 | Here is an example: 623 | 624 | ```js 625 | import React from 'react'; 626 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 627 | 628 | console.log(logo); // /logo.84287d09.png 629 | 630 | function Header() { 631 | // Import result is the URL of your image 632 | return <img src={logo} alt="Logo" />; 633 | } 634 | 635 | export default Header; 636 | ``` 637 | 638 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 639 | 640 | This works in CSS too: 641 | 642 | ```css 643 | .Logo { 644 | background-image: url(./logo.png); 645 | } 646 | ``` 647 | 648 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 649 | 650 | Please be advised that this is also a custom feature of Webpack. 651 | 652 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 653 | An alternative way of handling static assets is described in the next section. 654 | 655 | ## Using the `public` Folder 656 | 657 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 658 | 659 | ### Changing the HTML 660 | 661 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 662 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 663 | 664 | ### Adding Assets Outside of the Module System 665 | 666 | You can also add other assets to the `public` folder. 667 | 668 | Note that we normally encourage you to `import` assets in JavaScript files instead. 669 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 670 | This mechanism provides a number of benefits: 671 | 672 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 673 | * Missing files cause compilation errors instead of 404 errors for your users. 674 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 675 | 676 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 677 | 678 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 679 | 680 | Inside `index.html`, you can use it like this: 681 | 682 | ```html 683 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 684 | ``` 685 | 686 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 687 | 688 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 689 | 690 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 691 | 692 | ```js 693 | render() { 694 | // Note: this is an escape hatch and should be used sparingly! 695 | // Normally we recommend using `import` for getting asset URLs 696 | // as described in “Adding Images and Fonts” above this section. 697 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 698 | } 699 | ``` 700 | 701 | Keep in mind the downsides of this approach: 702 | 703 | * None of the files in `public` folder get post-processed or minified. 704 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 705 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 706 | 707 | ### When to Use the `public` Folder 708 | 709 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 710 | The `public` folder is useful as a workaround for a number of less common cases: 711 | 712 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 713 | * You have thousands of images and need to dynamically reference their paths. 714 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 715 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 716 | 717 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 718 | 719 | ## Using Global Variables 720 | 721 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 722 | 723 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 724 | 725 | ```js 726 | const $ = window.$; 727 | ``` 728 | 729 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 730 | 731 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 732 | 733 | ## Adding Bootstrap 734 | 735 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 736 | 737 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 738 | 739 | ```sh 740 | npm install --save react-bootstrap bootstrap@3 741 | ``` 742 | 743 | Alternatively you may use `yarn`: 744 | 745 | ```sh 746 | yarn add react-bootstrap bootstrap@3 747 | ``` 748 | 749 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 750 | 751 | ```js 752 | import 'bootstrap/dist/css/bootstrap.css'; 753 | import 'bootstrap/dist/css/bootstrap-theme.css'; 754 | // Put any other imports below so that CSS from your 755 | // components takes precedence over default styles. 756 | ``` 757 | 758 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 759 | 760 | ```js 761 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 762 | ``` 763 | 764 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 765 | 766 | ### Using a Custom Theme 767 | 768 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 769 | We suggest the following approach: 770 | 771 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 772 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 773 | * Install your own theme npm package as a dependency of your app. 774 | 775 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 776 | 777 | ## Adding Flow 778 | 779 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 780 | 781 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 782 | 783 | To add Flow to a Create React App project, follow these steps: 784 | 785 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 786 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 787 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 788 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 789 | 790 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 791 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 792 | In the future we plan to integrate it into Create React App even more closely. 793 | 794 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 795 | 796 | ## Adding Custom Environment Variables 797 | 798 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 799 | 800 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 801 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 802 | `REACT_APP_`. 803 | 804 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 805 | 806 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 807 | 808 | These environment variables will be defined for you on `process.env`. For example, having an environment 809 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 810 | 811 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 812 | 813 | These environment variables can be useful for displaying information conditionally based on where the project is 814 | deployed or consuming sensitive data that lives outside of version control. 815 | 816 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 817 | in the environment inside a `<form>`: 818 | 819 | ```jsx 820 | render() { 821 | return ( 822 | <div> 823 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 824 | <form> 825 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 826 | </form> 827 | </div> 828 | ); 829 | } 830 | ``` 831 | 832 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 833 | 834 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 835 | 836 | ```html 837 | <div> 838 | <small>You are running this application in <b>development</b> mode.</small> 839 | <form> 840 | <input type="hidden" value="abcdef" /> 841 | </form> 842 | </div> 843 | ``` 844 | 845 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 846 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 847 | a `.env` file. Both of these ways are described in the next few sections. 848 | 849 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 850 | 851 | ```js 852 | if (process.env.NODE_ENV !== 'production') { 853 | analytics.disable(); 854 | } 855 | ``` 856 | 857 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 858 | 859 | ### Referencing Environment Variables in the HTML 860 | 861 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 862 | 863 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 864 | 865 | ```html 866 | <title>%REACT_APP_WEBSITE_NAME% 867 | ``` 868 | 869 | Note that the caveats from the above section apply: 870 | 871 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 872 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 873 | 874 | ### Adding Temporary Environment Variables In Your Shell 875 | 876 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 877 | life of the shell session. 878 | 879 | #### Windows (cmd.exe) 880 | 881 | ```cmd 882 | set REACT_APP_SECRET_CODE=abcdef&&npm start 883 | ``` 884 | 885 | (Note: the lack of whitespace is intentional.) 886 | 887 | #### Linux, macOS (Bash) 888 | 889 | ```bash 890 | REACT_APP_SECRET_CODE=abcdef npm start 891 | ``` 892 | 893 | ### Adding Development Environment Variables In `.env` 894 | 895 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 896 | 897 | To define permanent environment variables, create a file called `.env` in the root of your project: 898 | 899 | ``` 900 | REACT_APP_SECRET_CODE=abcdef 901 | ``` 902 | 903 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 904 | 905 | #### What other `.env` files are can be used? 906 | 907 | >Note: this feature is **available with `react-scripts@1.0.0` and higher**. 908 | 909 | * `.env`: Default. 910 | * `.env.local`: Local overrides. **This file is loaded for all environments except test.** 911 | * `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 912 | * `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 913 | 914 | Files on the left have more priority than files on the right: 915 | 916 | * `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 917 | * `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 918 | * `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 919 | 920 | These variables will act as the defaults if the machine does not explicitly set them.
921 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 922 | 923 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 924 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 925 | 926 | ## Can I Use Decorators? 927 | 928 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
929 | Create React App doesn’t support decorator syntax at the moment because: 930 | 931 | * It is an experimental proposal and is subject to change. 932 | * The current specification version is not officially supported by Babel. 933 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 934 | 935 | However in many cases you can rewrite decorator-based code without decorators just as fine.
936 | Please refer to these two threads for reference: 937 | 938 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 939 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 940 | 941 | Create React App will add decorator support when the specification advances to a stable stage. 942 | 943 | ## Integrating with an API Backend 944 | 945 | These tutorials will help you to integrate your app with an API backend running on another port, 946 | using `fetch()` to access it. 947 | 948 | ### Node 949 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 950 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 951 | 952 | ### Ruby on Rails 953 | 954 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 955 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 956 | 957 | ## Proxying API Requests in Development 958 | 959 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 960 | 961 | People often serve the front-end React app from the same host and port as their backend implementation.
962 | For example, a production setup might look like this after the app is deployed: 963 | 964 | ``` 965 | / - static server returns index.html with React app 966 | /todos - static server returns index.html with React app 967 | /api/todos - server handles any /api/* requests using the backend implementation 968 | ``` 969 | 970 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 971 | 972 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 973 | 974 | ```js 975 | "proxy": "http://localhost:4000", 976 | ``` 977 | 978 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 979 | 980 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 981 | 982 | ``` 983 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 984 | ``` 985 | 986 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 987 | 988 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
989 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 990 | 991 | * [Configure the proxy yourself](#configuring-the-proxy-manually) 992 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 993 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 994 | 995 | ### "Invalid Host Header" Errors After Configuring Proxy 996 | 997 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 998 | 999 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 1000 | 1001 | >Invalid Host header 1002 | 1003 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 1004 | 1005 | ``` 1006 | HOST=mypublicdevhost.com 1007 | ``` 1008 | 1009 | If you restart the development server now and load the app from the specified host, it should work. 1010 | 1011 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 1012 | 1013 | ``` 1014 | # NOTE: THIS IS DANGEROUS! 1015 | # It exposes your machine to attacks from the websites you visit. 1016 | DANGEROUSLY_DISABLE_HOST_CHECK=true 1017 | ``` 1018 | 1019 | We don’t recommend this approach. 1020 | 1021 | ### Configuring the Proxy Manually 1022 | 1023 | >Note: this feature is available with `react-scripts@1.0.0` and higher. 1024 | 1025 | If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
1026 | You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. 1027 | ```js 1028 | { 1029 | // ... 1030 | "proxy": { 1031 | "/api": { 1032 | "target": "", 1033 | "ws": true 1034 | // ... 1035 | } 1036 | } 1037 | // ... 1038 | } 1039 | ``` 1040 | 1041 | All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. 1042 | 1043 | If you need to specify multiple proxies, you may do so by specifying additional entries. 1044 | You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. 1045 | ```js 1046 | { 1047 | // ... 1048 | "proxy": { 1049 | // Matches any request starting with /api 1050 | "/api": { 1051 | "target": "", 1052 | "ws": true 1053 | // ... 1054 | }, 1055 | // Matches any request starting with /foo 1056 | "/foo": { 1057 | "target": "", 1058 | "ssl": true, 1059 | "pathRewrite": { 1060 | "^/foo": "/foo/beta" 1061 | } 1062 | // ... 1063 | }, 1064 | // Matches /bar/abc.html but not /bar/sub/def.html 1065 | "/bar/*.html": { 1066 | "target": "", 1067 | // ... 1068 | }, 1069 | // Matches /baz/abc.html and /baz/sub/def.html 1070 | "/baz/**/*.html": { 1071 | "target": "" 1072 | // ... 1073 | } 1074 | } 1075 | // ... 1076 | } 1077 | ``` 1078 | 1079 | ### Configuring a WebSocket Proxy 1080 | 1081 | When setting up a WebSocket proxy, there are a some extra considerations to be aware of. 1082 | 1083 | If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). 1084 | 1085 | There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). 1086 | 1087 | Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). 1088 | 1089 | Either way, you can proxy WebSocket requests manually in `package.json`: 1090 | 1091 | ```js 1092 | { 1093 | // ... 1094 | "proxy": { 1095 | "/socket": { 1096 | // Your compatible WebSocket server 1097 | "target": "ws://", 1098 | // Tell http-proxy-middleware that this is a WebSocket proxy. 1099 | // Also allows you to proxy WebSocket requests without an additional HTTP request 1100 | // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade 1101 | "ws": true 1102 | // ... 1103 | } 1104 | } 1105 | // ... 1106 | } 1107 | ``` 1108 | 1109 | ## Using HTTPS in Development 1110 | 1111 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 1112 | 1113 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 1114 | 1115 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 1116 | 1117 | #### Windows (cmd.exe) 1118 | 1119 | ```cmd 1120 | set HTTPS=true&&npm start 1121 | ``` 1122 | 1123 | (Note: the lack of whitespace is intentional.) 1124 | 1125 | #### Linux, macOS (Bash) 1126 | 1127 | ```bash 1128 | HTTPS=true npm start 1129 | ``` 1130 | 1131 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1132 | 1133 | ## Generating Dynamic `` Tags on the Server 1134 | 1135 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1136 | 1137 | ```html 1138 | 1139 | 1140 | 1141 | 1142 | 1143 | ``` 1144 | 1145 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 1146 | 1147 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 1148 | 1149 | ## Pre-Rendering into Static HTML Files 1150 | 1151 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 1152 | 1153 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1154 | 1155 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1156 | 1157 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1158 | 1159 | ## Injecting Data from the Server into the Page 1160 | 1161 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1162 | 1163 | ```js 1164 | 1165 | 1166 | 1167 | 1170 | ``` 1171 | 1172 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 1173 | 1174 | ## Running Tests 1175 | 1176 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1177 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 1178 | 1179 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 1180 | 1181 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 1182 | 1183 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 1184 | 1185 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 1186 | 1187 | ### Filename Conventions 1188 | 1189 | Jest will look for test files with any of the following popular naming conventions: 1190 | 1191 | * Files with `.js` suffix in `__tests__` folders. 1192 | * Files with `.test.js` suffix. 1193 | * Files with `.spec.js` suffix. 1194 | 1195 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1196 | 1197 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 1198 | 1199 | ### Command Line Interface 1200 | 1201 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 1202 | 1203 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 1204 | 1205 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1206 | 1207 | ### Version Control Integration 1208 | 1209 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 1210 | 1211 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 1212 | 1213 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 1214 | 1215 | ### Writing Tests 1216 | 1217 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 1218 | 1219 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1220 | 1221 | ```js 1222 | import sum from './sum'; 1223 | 1224 | it('sums numbers', () => { 1225 | expect(sum(1, 2)).toEqual(3); 1226 | expect(sum(2, 2)).toEqual(4); 1227 | }); 1228 | ``` 1229 | 1230 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1231 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. 1232 | 1233 | ### Testing Components 1234 | 1235 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 1236 | 1237 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 1238 | 1239 | ```js 1240 | import React from 'react'; 1241 | import ReactDOM from 'react-dom'; 1242 | import App from './App'; 1243 | 1244 | it('renders without crashing', () => { 1245 | const div = document.createElement('div'); 1246 | ReactDOM.render(, div); 1247 | }); 1248 | ``` 1249 | 1250 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. 1251 | 1252 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. 1253 | 1254 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: 1255 | 1256 | ```sh 1257 | npm install --save enzyme react-test-renderer 1258 | ``` 1259 | 1260 | Alternatively you may use `yarn`: 1261 | 1262 | ```sh 1263 | yarn add enzyme react-test-renderer 1264 | ``` 1265 | 1266 | You can write a smoke test with it too: 1267 | 1268 | ```js 1269 | import React from 'react'; 1270 | import { shallow } from 'enzyme'; 1271 | import App from './App'; 1272 | 1273 | it('renders without crashing', () => { 1274 | shallow(); 1275 | }); 1276 | ``` 1277 | 1278 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `