├── 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 |
6 | {label}
7 |
15 |
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 |
26 | You need to enable JavaScript to run this app.
27 |
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 |
48 |
55 |
56 |
57 | Reset
58 |
59 |
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
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 | 
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 `` that throws, this test will pass. Shallow rendering is great for isolated unit tests, but you may still want to create some full rendering tests to ensure the components integrate correctly. Enzyme supports [full rendering with `mount()`](http://airbnb.io/enzyme/docs/api/mount.html), and you can also use it for testing state changes and component lifecycle.
1279 |
1280 | You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testing techniques. Enzyme documentation uses Chai and Sinon for assertions but you don’t have to use them because Jest provides built-in `expect()` and `jest.fn()` for spies.
1281 |
1282 | Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
1283 |
1284 | ```js
1285 | import React from 'react';
1286 | import { shallow } from 'enzyme';
1287 | import App from './App';
1288 |
1289 | it('renders welcome message', () => {
1290 | const wrapper = shallow( );
1291 | const welcome = Welcome to React ;
1292 | // expect(wrapper.contains(welcome)).to.equal(true);
1293 | expect(wrapper.contains(welcome)).toEqual(true);
1294 | });
1295 | ```
1296 |
1297 | All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1298 | Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below.
1299 |
1300 | Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written simpler with jest-enzyme.
1301 |
1302 | ```js
1303 | expect(wrapper).toContainReact(welcome)
1304 | ```
1305 |
1306 | To enable this, install `jest-enzyme`:
1307 |
1308 | ```sh
1309 | npm install --save jest-enzyme
1310 | ```
1311 |
1312 | Alternatively you may use `yarn`:
1313 |
1314 | ```sh
1315 | yarn add jest-enzyme
1316 | ```
1317 |
1318 | Import it in [`src/setupTests.js`](#initializing-test-environment) to make its matchers available in every test:
1319 |
1320 | ```js
1321 | import 'jest-enzyme';
1322 | ```
1323 |
1324 | ### Using Third Party Assertion Libraries
1325 |
1326 | We recommend that you use `expect()` for assertions and `jest.fn()` for spies. If you are having issues with them please [file those against Jest](https://github.com/facebook/jest/issues/new), and we’ll fix them. We intend to keep making them better for React, supporting, for example, [pretty-printing React elements as JSX](https://github.com/facebook/jest/pull/1566).
1327 |
1328 | However, if you are used to other libraries, such as [Chai](http://chaijs.com/) and [Sinon](http://sinonjs.org/), or if you have existing code using them that you’d like to port over, you can import them normally like this:
1329 |
1330 | ```js
1331 | import sinon from 'sinon';
1332 | import { expect } from 'chai';
1333 | ```
1334 |
1335 | and then use them in your tests like you normally do.
1336 |
1337 | ### Initializing Test Environment
1338 |
1339 | >Note: this feature is available with `react-scripts@0.4.0` and higher.
1340 |
1341 | If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a `src/setupTests.js` to your project. It will be automatically executed before running your tests.
1342 |
1343 | For example:
1344 |
1345 | #### `src/setupTests.js`
1346 | ```js
1347 | const localStorageMock = {
1348 | getItem: jest.fn(),
1349 | setItem: jest.fn(),
1350 | clear: jest.fn()
1351 | };
1352 | global.localStorage = localStorageMock
1353 | ```
1354 |
1355 | ### Focusing and Excluding Tests
1356 |
1357 | You can replace `it()` with `xit()` to temporarily exclude a test from being executed.
1358 | Similarly, `fit()` lets you focus on a specific test without running any other tests.
1359 |
1360 | ### Coverage Reporting
1361 |
1362 | Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.
1363 | Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this:
1364 |
1365 | 
1366 |
1367 | Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow.
1368 |
1369 | ### Continuous Integration
1370 |
1371 | By default `npm test` runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called `CI`.
1372 |
1373 | When creating a build of your application with `npm run build` linter warnings are not checked by default. Like `npm test`, you can force the build to perform a linter warning check by setting the environment variable `CI`. If any warnings are encountered then the build fails.
1374 |
1375 | Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
1376 |
1377 | ### On CI servers
1378 | #### Travis CI
1379 |
1380 | 1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page.
1381 | 1. Add a `.travis.yml` file to your git repository.
1382 | ```
1383 | language: node_js
1384 | node_js:
1385 | - 6
1386 | cache:
1387 | directories:
1388 | - node_modules
1389 | script:
1390 | - npm run build
1391 | - npm test
1392 | ```
1393 | 1. Trigger your first build with a git push.
1394 | 1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
1395 |
1396 | #### CircleCI
1397 |
1398 | Follow [this article](https://medium.com/@knowbody/circleci-and-zeits-now-sh-c9b7eebcd3c1) to set up CircleCI with a Create React App project.
1399 |
1400 | ### On your own environment
1401 | ##### Windows (cmd.exe)
1402 |
1403 | ```cmd
1404 | set CI=true&&npm test
1405 | ```
1406 |
1407 | ```cmd
1408 | set CI=true&&npm run build
1409 | ```
1410 |
1411 | (Note: the lack of whitespace is intentional.)
1412 |
1413 | ##### Linux, macOS (Bash)
1414 |
1415 | ```bash
1416 | CI=true npm test
1417 | ```
1418 |
1419 | ```bash
1420 | CI=true npm run build
1421 | ```
1422 |
1423 | The test command will force Jest to run tests once instead of launching the watcher.
1424 |
1425 | > If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
1426 |
1427 | The build command will check for linter warnings and fail if any are found.
1428 |
1429 | ### Disabling jsdom
1430 |
1431 | By default, the `package.json` of the generated project looks like this:
1432 |
1433 | ```js
1434 | "scripts": {
1435 | "start": "react-scripts start",
1436 | "build": "react-scripts build",
1437 | "test": "react-scripts test --env=jsdom"
1438 | ```
1439 |
1440 | If you know that none of your tests depend on [jsdom](https://github.com/tmpvar/jsdom), you can safely remove `--env=jsdom`, and your tests will run faster:
1441 |
1442 | ```diff
1443 | "scripts": {
1444 | "start": "react-scripts start",
1445 | "build": "react-scripts build",
1446 | - "test": "react-scripts test --env=jsdom"
1447 | + "test": "react-scripts test"
1448 | ```
1449 |
1450 | To help you make up your mind, here is a list of APIs that **need jsdom**:
1451 |
1452 | * Any browser globals like `window` and `document`
1453 | * [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render)
1454 | * [`TestUtils.renderIntoDocument()`](https://facebook.github.io/react/docs/test-utils.html#renderintodocument) ([a shortcut](https://github.com/facebook/react/blob/34761cf9a252964abfaab6faf74d473ad95d1f21/src/test/ReactTestUtils.js#L83-L91) for the above)
1455 | * [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1456 |
1457 | In contrast, **jsdom is not needed** for the following APIs:
1458 |
1459 | * [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering)
1460 | * [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1461 |
1462 | Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html).
1463 |
1464 | ### Snapshot Testing
1465 |
1466 | Snapshot testing is a feature of Jest that automatically generates text snapshots of your components and saves them on the disk so if the UI output changes, you get notified without manually writing any assertions on the component output. [Read more about snapshot testing.](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html)
1467 |
1468 | ### Editor Integration
1469 |
1470 | If you use [Visual Studio Code](https://code.visualstudio.com), there is a [Jest extension](https://github.com/orta/vscode-jest) which works with Create React App out of the box. This provides a lot of IDE-like features while using a text editor: showing the status of a test run with potential fail messages inline, starting and stopping the watcher automatically, and offering one-click snapshot updates.
1471 |
1472 | 
1473 |
1474 | ## Developing Components in Isolation
1475 |
1476 | Usually, in an app, you have a lot of UI components, and each of them has many different states.
1477 | For an example, a simple button component could have following states:
1478 |
1479 | * In a regular state, with a text label.
1480 | * In the disabled mode.
1481 | * In a loading state.
1482 |
1483 | Usually, it’s hard to see these states without running a sample app or some examples.
1484 |
1485 | Create React App doesn’t include any tools for this by default, but you can easily add [Storybook for React](https://storybook.js.org) ([source](https://github.com/storybooks/storybook)) or [React Styleguidist](https://react-styleguidist.js.org/) ([source](https://github.com/styleguidist/react-styleguidist)) to your project. **These are third-party tools that let you develop components and see all their states in isolation from your app**.
1486 |
1487 | 
1488 |
1489 | You can also deploy your Storybook or style guide as a static app. This way, everyone in your team can view and review different states of UI components without starting a backend server or creating an account in your app.
1490 |
1491 | ### Getting Started with Storybook
1492 |
1493 | Storybook is a development environment for React UI components. It allows you to browse a component library, view the different states of each component, and interactively develop and test components.
1494 |
1495 | First, install the following npm package globally:
1496 |
1497 | ```sh
1498 | npm install -g @storybook/cli
1499 | ```
1500 |
1501 | Then, run the following command inside your app’s directory:
1502 |
1503 | ```sh
1504 | getstorybook
1505 | ```
1506 |
1507 | After that, follow the instructions on the screen.
1508 |
1509 | Learn more about React Storybook:
1510 |
1511 | * Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook)
1512 | * [GitHub Repo](https://github.com/storybooks/storybook)
1513 | * [Documentation](https://storybook.js.org/basics/introduction/)
1514 | * [Snapshot Testing UI](https://github.com/storybooks/storybook/tree/master/addons/storyshots) with Storybook + addon/storyshot
1515 |
1516 | ### Getting Started with Styleguidist
1517 |
1518 | Styleguidist combines a style guide, where all your components are presented on a single page with their props documentation and usage examples, with an environment for developing components in isolation, similar to Storybook. In Styleguidist you write examples in Markdown, where each code snippet is rendered as a live editable playground.
1519 |
1520 | First, install Styleguidist:
1521 |
1522 | ```sh
1523 | npm install --save react-styleguidist
1524 | ```
1525 |
1526 | Alternatively you may use `yarn`:
1527 |
1528 | ```sh
1529 | yarn add react-styleguidist
1530 | ```
1531 |
1532 | Then, add these scripts to your `package.json`:
1533 |
1534 | ```diff
1535 | "scripts": {
1536 | + "styleguide": "styleguidist server",
1537 | + "styleguide:build": "styleguidist build",
1538 | "start": "react-scripts start",
1539 | ```
1540 |
1541 | Then, run the following command inside your app’s directory:
1542 |
1543 | ```sh
1544 | npm run styleguide
1545 | ```
1546 |
1547 | After that, follow the instructions on the screen.
1548 |
1549 | Learn more about React Styleguidist:
1550 |
1551 | * [GitHub Repo](https://github.com/styleguidist/react-styleguidist)
1552 | * [Documentation](https://react-styleguidist.js.org/docs/getting-started.html)
1553 |
1554 | ## Making a Progressive Web App
1555 |
1556 | By default, the production build is a fully functional, offline-first
1557 | [Progressive Web App](https://developers.google.com/web/progressive-web-apps/).
1558 |
1559 | Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience:
1560 |
1561 | * All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background.
1562 | * Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the Subway.
1563 | * On mobile devices, your app can be added directly to the user's home screen, app icon and all. You can also re-engage users using web **push notifications**. This eliminates the need for the app store.
1564 |
1565 | The [`sw-precache-webpack-plugin`](https://github.com/goldhand/sw-precache-webpack-plugin)
1566 | is integrated into production configuration,
1567 | and it will take care of generating a service worker file that will automatically
1568 | precache all of your local assets and keep them up to date as you deploy updates.
1569 | The service worker will use a [cache-first strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network)
1570 | for handling all requests for local assets, including the initial HTML, ensuring
1571 | that your web app is reliably fast, even on a slow or unreliable network.
1572 |
1573 | ### Opting Out of Caching
1574 |
1575 | If you would prefer not to enable service workers prior to your initial
1576 | production deployment, then remove the call to `serviceWorkerRegistration.register()`
1577 | from [`src/index.js`](src/index.js).
1578 |
1579 | If you had previously enabled service workers in your production deployment and
1580 | have decided that you would like to disable them for all your existing users,
1581 | you can swap out the call to `serviceWorkerRegistration.register()` in
1582 | [`src/index.js`](src/index.js) with a call to `serviceWorkerRegistration.unregister()`.
1583 | After the user visits a page that has `serviceWorkerRegistration.unregister()`,
1584 | the service worker will be uninstalled. Note that depending on how `/service-worker.js` is served,
1585 | it may take up to 24 hours for the cache to be invalidated.
1586 |
1587 | ### Offline-First Considerations
1588 |
1589 | 1. Service workers [require HTTPS](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers#you_need_https),
1590 | although to facilitate local testing, that policy
1591 | [does not apply to `localhost`](http://stackoverflow.com/questions/34160509/options-for-testing-service-workers-via-http/34161385#34161385).
1592 | If your production web server does not support HTTPS, then the service worker
1593 | registration will fail, but the rest of your web app will remain functional.
1594 |
1595 | 1. Service workers are [not currently supported](https://jakearchibald.github.io/isserviceworkerready/)
1596 | in all web browsers. Service worker registration [won't be attempted](src/registerServiceWorker.js)
1597 | on browsers that lack support.
1598 |
1599 | 1. The service worker is only enabled in the [production environment](#deployment),
1600 | e.g. the output of `npm run build`. It's recommended that you do not enable an
1601 | offline-first service worker in a development environment, as it can lead to
1602 | frustration when previously cached assets are used and do not include the latest
1603 | changes you've made locally.
1604 |
1605 | 1. If you *need* to test your offline-first service worker locally, build
1606 | the application (using `npm run build`) and run a simple http server from your
1607 | build directory. After running the build script, `create-react-app` will give
1608 | instructions for one way to test your production build locally and the [deployment instructions](#deployment) have
1609 | instructions for using other methods. *Be sure to always use an
1610 | incognito window to avoid complications with your browser cache.*
1611 |
1612 | 1. If possible, configure your production environment to serve the generated
1613 | `service-worker.js` [with HTTP caching disabled](http://stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours).
1614 | If that's not possible—[GitHub Pages](#github-pages), for instance, does not
1615 | allow you to change the default 10 minute HTTP cache lifetime—then be aware
1616 | that if you visit your production site, and then revisit again before
1617 | `service-worker.js` has expired from your HTTP cache, you'll continue to get
1618 | the previously cached assets from the service worker. If you have an immediate
1619 | need to view your updated production deployment, performing a shift-refresh
1620 | will temporarily disable the service worker and retrieve all assets from the
1621 | network.
1622 |
1623 | 1. Users aren't always familiar with offline-first web apps. It can be useful to
1624 | [let the user know](https://developers.google.com/web/fundamentals/instant-and-offline/offline-ux#inform_the_user_when_the_app_is_ready_for_offline_consumption)
1625 | when the service worker has finished populating your caches (showing a "This web
1626 | app works offline!" message) and also let them know when the service worker has
1627 | fetched the latest updates that will be available the next time they load the
1628 | page (showing a "New content is available; please refresh." message). Showing
1629 | this messages is currently left as an exercise to the developer, but as a
1630 | starting point, you can make use of the logic included in [`src/registerServiceWorker.js`](src/registerServiceWorker.js), which
1631 | demonstrates which service worker lifecycle events to listen for to detect each
1632 | scenario, and which as a default, just logs appropriate messages to the
1633 | JavaScript console.
1634 |
1635 | 1. By default, the generated service worker file will not intercept or cache any
1636 | cross-origin traffic, like HTTP [API requests](#integrating-with-an-api-backend),
1637 | images, or embeds loaded from a different domain. If you would like to use a
1638 | runtime caching strategy for those requests, you can [`eject`](#npm-run-eject)
1639 | and then configure the
1640 | [`runtimeCaching`](https://github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject)
1641 | option in the `SWPrecacheWebpackPlugin` section of
1642 | [`webpack.config.prod.js`](../config/webpack.config.prod.js).
1643 |
1644 | ### Progressive Web App Metadata
1645 |
1646 | The default configuration includes a web app manifest located at
1647 | [`public/manifest.json`](public/manifest.json), that you can customize with
1648 | details specific to your web application.
1649 |
1650 | When a user adds a web app to their homescreen using Chrome or Firefox on
1651 | Android, the metadata in [`manifest.json`](public/manifest.json) determines what
1652 | icons, names, and branding colors to use when the web app is displayed.
1653 | [The Web App Manifest guide](https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/)
1654 | provides more context about what each field means, and how your customizations
1655 | will affect your users' experience.
1656 |
1657 | ## Analyzing the Bundle Size
1658 |
1659 | [Source map explorer](https://www.npmjs.com/package/source-map-explorer) analyzes
1660 | JavaScript bundles using the source maps. This helps you understand where code
1661 | bloat is coming from.
1662 |
1663 | To add Source map explorer to a Create React App project, follow these steps:
1664 |
1665 | ```sh
1666 | npm install --save source-map-explorer
1667 | ```
1668 |
1669 | Alternatively you may use `yarn`:
1670 |
1671 | ```sh
1672 | yarn add source-map-explorer
1673 | ```
1674 |
1675 | Then in `package.json`, add the following line to `scripts`:
1676 |
1677 | ```diff
1678 | "scripts": {
1679 | + "analyze": "source-map-explorer build/static/js/main.*",
1680 | "start": "react-scripts start",
1681 | "build": "react-scripts build",
1682 | "test": "react-scripts test --env=jsdom",
1683 | ```
1684 |
1685 | Then to analyze the bundle run the production build then run the analyze
1686 | script.
1687 |
1688 | ```
1689 | npm run build
1690 | npm run analyze
1691 | ```
1692 |
1693 | ## Deployment
1694 |
1695 | `npm run build` creates a `build` directory with a production build of your app. Set up your favourite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main..js` are served with the contents of the `/static/js/main..js` file.
1696 |
1697 | ### Static Server
1698 |
1699 | For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest:
1700 |
1701 | ```sh
1702 | npm install -g serve
1703 | serve -s build
1704 | ```
1705 |
1706 | The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-p` or `--port` flags.
1707 |
1708 | Run this command to get a full list of the options available:
1709 |
1710 | ```sh
1711 | serve -h
1712 | ```
1713 |
1714 | ### Other Solutions
1715 |
1716 | You don’t necessarily need a static server in order to run a Create React App project in production. It works just as fine integrated into an existing dynamic one.
1717 |
1718 | Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
1719 |
1720 | ```javascript
1721 | const express = require('express');
1722 | const path = require('path');
1723 | const app = express();
1724 |
1725 | app.use(express.static(path.join(__dirname, 'build')));
1726 |
1727 | app.get('/', function (req, res) {
1728 | res.sendFile(path.join(__dirname, 'build', 'index.html'));
1729 | });
1730 |
1731 | app.listen(9000);
1732 | ```
1733 |
1734 | The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node.
1735 |
1736 | The `build` folder with static assets is the only output produced by Create React App.
1737 |
1738 | However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like `/todos/42` in your single-page app.
1739 |
1740 | ### Serving Apps with Client-Side Routing
1741 |
1742 | If you use routers that use the HTML5 [`pushState` history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) under the hood (for example, [React Router](https://github.com/ReactTraining/react-router) with `browserHistory`), many static file servers will fail. For example, if you used React Router with a route for `/todos/42`, the development server will respond to `localhost:3000/todos/42` properly, but an Express serving a production build as above will not.
1743 |
1744 | This is because when there is a fresh page load for a `/todos/42`, the server looks for the file `build/todos/42` and does not find it. The server needs to be configured to respond to a request to `/todos/42` by serving `index.html`. For example, we can amend our Express example above to serve `index.html` for any unknown paths:
1745 |
1746 | ```diff
1747 | app.use(express.static(path.join(__dirname, 'build')));
1748 |
1749 | -app.get('/', function (req, res) {
1750 | +app.get('/*', function (req, res) {
1751 | res.sendFile(path.join(__dirname, 'build', 'index.html'));
1752 | });
1753 | ```
1754 |
1755 | If you’re using [Apache HTTP Server](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this:
1756 |
1757 | ```
1758 | Options -MultiViews
1759 | RewriteEngine On
1760 | RewriteCond %{REQUEST_FILENAME} !-f
1761 | RewriteRule ^ index.html [QSA,L]
1762 | ```
1763 |
1764 | It will get copied to the `build` folder when you run `npm run build`.
1765 |
1766 | If you’re using [Apache Tomcat](http://tomcat.apache.org/), you need to follow [this Stack Overflow answer](https://stackoverflow.com/a/41249464/4878474).
1767 |
1768 | Now requests to `/todos/42` will be handled correctly both in development and in production.
1769 |
1770 | On a production build, and in a browser that supports [service workers](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers),
1771 | the service worker will automatically handle all navigation requests, like for
1772 | `/todos/42`, by serving the cached copy of your `index.html`. This
1773 | service worker navigation routing can be configured or disabled by
1774 | [`eject`ing](#npm-run-eject) and then modifying the
1775 | [`navigateFallback`](https://github.com/GoogleChrome/sw-precache#navigatefallback-string)
1776 | and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp)
1777 | options of the `SWPreachePlugin` [configuration](../config/webpack.config.prod.js).
1778 |
1779 | ### Building for Relative Paths
1780 |
1781 | By default, Create React App produces a build assuming your app is hosted at the server root.
1782 | To override this, specify the `homepage` in your `package.json`, for example:
1783 |
1784 | ```js
1785 | "homepage": "http://mywebsite.com/relativepath",
1786 | ```
1787 |
1788 | This will let Create React App correctly infer the root path to use in the generated HTML file.
1789 |
1790 | **Note**: If you are using `react-router@^4`, you can root ` `s using the `basename` prop on any ``.
1791 | More information [here](https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string).
1792 |
1793 | For example:
1794 | ```js
1795 |
1796 | // renders
1797 | ```
1798 |
1799 | #### Serving the Same Build from Different Paths
1800 |
1801 | >Note: this feature is available with `react-scripts@0.9.0` and higher.
1802 |
1803 | If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`:
1804 |
1805 | ```js
1806 | "homepage": ".",
1807 | ```
1808 |
1809 | This will make sure that all the asset paths are relative to `index.html`. You will then be able to move your app from `http://mywebsite.com` to `http://mywebsite.com/relativepath` or even `http://mywebsite.com/relative/path` without having to rebuild it.
1810 |
1811 | ### Azure
1812 |
1813 | See [this](https://medium.com/@to_pe/deploying-create-react-app-on-microsoft-azure-c0f6686a4321) blog post on how to deploy your React app to [Microsoft Azure](https://azure.microsoft.com/).
1814 |
1815 | ### Firebase
1816 |
1817 | Install the Firebase CLI if you haven’t already by running `npm install -g firebase-tools`. Sign up for a [Firebase account](https://console.firebase.google.com/) and create a new project. Run `firebase login` and login with your previous created Firebase account.
1818 |
1819 | Then run the `firebase init` command from your project’s root. You need to choose the **Hosting: Configure and deploy Firebase Hosting sites** and choose the Firebase project you created in the previous step. You will need to agree with `database.rules.json` being created, choose `build` as the public directory, and also agree to **Configure as a single-page app** by replying with `y`.
1820 |
1821 | ```sh
1822 | === Project Setup
1823 |
1824 | First, let's associate this project directory with a Firebase project.
1825 | You can create multiple project aliases by running firebase use --add,
1826 | but for now we'll just set up a default project.
1827 |
1828 | ? What Firebase project do you want to associate as default? Example app (example-app-fd690)
1829 |
1830 | === Database Setup
1831 |
1832 | Firebase Realtime Database Rules allow you to define how your data should be
1833 | structured and when your data can be read from and written to.
1834 |
1835 | ? What file should be used for Database Rules? database.rules.json
1836 | ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json.
1837 | Future modifications to database.rules.json will update Database Rules when you run
1838 | firebase deploy.
1839 |
1840 | === Hosting Setup
1841 |
1842 | Your public directory is the folder (relative to your project directory) that
1843 | will contain Hosting assets to uploaded with firebase deploy. If you
1844 | have a build process for your assets, use your build's output directory.
1845 |
1846 | ? What do you want to use as your public directory? build
1847 | ? Configure as a single-page app (rewrite all urls to /index.html)? Yes
1848 | ✔ Wrote build/index.html
1849 |
1850 | i Writing configuration info to firebase.json...
1851 | i Writing project information to .firebaserc...
1852 |
1853 | ✔ Firebase initialization complete!
1854 | ```
1855 |
1856 | Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`.
1857 |
1858 | ```sh
1859 | === Deploying to 'example-app-fd690'...
1860 |
1861 | i deploying database, hosting
1862 | ✔ database: rules ready to deploy.
1863 | i hosting: preparing build directory for upload...
1864 | Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully
1865 | ✔ hosting: 8 files uploaded successfully
1866 | i starting release process (may take several minutes)...
1867 |
1868 | ✔ Deploy complete!
1869 |
1870 | Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
1871 | Hosting URL: https://example-app-fd690.firebaseapp.com
1872 | ```
1873 |
1874 | For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup).
1875 |
1876 | ### GitHub Pages
1877 |
1878 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
1879 |
1880 | #### Step 1: Add `homepage` to `package.json`
1881 |
1882 | **The step below is important!**
1883 | **If you skip it, your app will not deploy correctly.**
1884 |
1885 | Open your `package.json` and add a `homepage` field:
1886 |
1887 | ```js
1888 | "homepage": "https://myusername.github.io/my-app",
1889 | ```
1890 |
1891 | Create React App uses the `homepage` field to determine the root URL in the built HTML file.
1892 |
1893 | #### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`
1894 |
1895 | Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
1896 |
1897 | To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run:
1898 |
1899 | ```sh
1900 | npm install --save gh-pages
1901 | ```
1902 |
1903 | Alternatively you may use `yarn`:
1904 |
1905 | ```sh
1906 | yarn add gh-pages
1907 | ```
1908 |
1909 | Add the following scripts in your `package.json`:
1910 |
1911 | ```diff
1912 | "scripts": {
1913 | + "predeploy": "npm run build",
1914 | + "deploy": "gh-pages -d build",
1915 | "start": "react-scripts start",
1916 | "build": "react-scripts build",
1917 | ```
1918 |
1919 | The `predeploy` script will run automatically before `deploy` is run.
1920 |
1921 | #### Step 3: Deploy the site by running `npm run deploy`
1922 |
1923 | Then run:
1924 |
1925 | ```sh
1926 | npm run deploy
1927 | ```
1928 |
1929 | #### Step 4: Ensure your project’s settings use `gh-pages`
1930 |
1931 | Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch:
1932 |
1933 |
1934 |
1935 | #### Step 5: Optionally, configure the domain
1936 |
1937 | You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder.
1938 |
1939 | #### Notes on client-side routing
1940 |
1941 | GitHub Pages doesn’t support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:
1942 |
1943 | * You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to `hashHistory` for this effect, but the URL will be longer and more verbose (for example, `http://user.github.io/todomvc/#/todos/42?_k=yknaj`). [Read more](https://reacttraining.com/react-router/web/api/Router) about different history implementations in React Router.
1944 | * Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your `index.html` page with a special redirect parameter. You would need to add a `404.html` file with the redirection code to the `build` folder before deploying your project, and you’ll need to add code handling the redirect parameter to `index.html`. You can find a detailed explanation of this technique [in this guide](https://github.com/rafrex/spa-github-pages).
1945 |
1946 | ### Heroku
1947 |
1948 | Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).
1949 | You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration).
1950 |
1951 | #### Resolving Heroku Deployment Errors
1952 |
1953 | Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases.
1954 |
1955 | ##### "Module not found: Error: Cannot resolve 'file' or 'directory'"
1956 |
1957 | If you get something like this:
1958 |
1959 | ```
1960 | remote: Failed to create a production build. Reason:
1961 | remote: Module not found: Error: Cannot resolve 'file' or 'directory'
1962 | MyDirectory in /tmp/build_1234/src
1963 | ```
1964 |
1965 | It means you need to ensure that the lettercase of the file or directory you `import` matches the one you see on your filesystem or on GitHub.
1966 |
1967 | This is important because Linux (the operating system used by Heroku) is case sensitive. So `MyDirectory` and `mydirectory` are two distinct directories and thus, even though the project builds locally, the difference in case breaks the `import` statements on Heroku remotes.
1968 |
1969 | ##### "Could not find a required file."
1970 |
1971 | If you exclude or ignore necessary files from the package you will see a error similar this one:
1972 |
1973 | ```
1974 | remote: Could not find a required file.
1975 | remote: Name: `index.html`
1976 | remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public
1977 | remote:
1978 | remote: npm ERR! Linux 3.13.0-105-generic
1979 | remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build"
1980 | ```
1981 |
1982 | In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local `.gitignore` or `~/.gitignore_global`.
1983 |
1984 | ### Modulus
1985 |
1986 | See the [Modulus blog post](http://blog.modulus.io/deploying-react-apps-on-modulus) on how to deploy your react app to Modulus.
1987 |
1988 | ### Netlify
1989 |
1990 | **To do a manual deploy to Netlify’s CDN:**
1991 |
1992 | ```sh
1993 | npm install netlify-cli
1994 | netlify deploy
1995 | ```
1996 |
1997 | Choose `build` as the path to deploy.
1998 |
1999 | **To setup continuous delivery:**
2000 |
2001 | With this setup Netlify will build and deploy when you push to git or open a pull request:
2002 |
2003 | 1. [Start a new netlify project](https://app.netlify.com/signup)
2004 | 2. Pick your Git hosting service and select your repository
2005 | 3. Click `Build your site`
2006 |
2007 | **Support for client-side routing:**
2008 |
2009 | To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules:
2010 |
2011 | ```
2012 | /* /index.html 200
2013 | ```
2014 |
2015 | When you build the project, Create React App will place the `public` folder contents into the build output.
2016 |
2017 | ### Now
2018 |
2019 | [now](https://zeit.co/now) offers a zero-configuration single-command deployment. You can use `now` to deploy your app for free.
2020 |
2021 | 1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
2022 |
2023 | 2. Build your app by running `npm run build`.
2024 |
2025 | 3. Move into the build directory by running `cd build`.
2026 |
2027 | 4. Run `now --name your-project-name` from within the build directory. You will see a **now.sh** URL in your output like this:
2028 |
2029 | ```
2030 | > Ready! https://your-project-name-tpspyhtdtk.now.sh (copied to clipboard)
2031 | ```
2032 |
2033 | Paste that URL into your browser when the build is complete, and you will see your deployed app.
2034 |
2035 | Details are available in [this article.](https://zeit.co/blog/unlimited-static)
2036 |
2037 | ### S3 and CloudFront
2038 |
2039 | See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-to-s3-or-cloudfront-48dae4ce0af) on how to deploy your React app to Amazon Web Services [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/).
2040 |
2041 | ### Surge
2042 |
2043 | Install the Surge CLI if you haven’t already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account.
2044 |
2045 | When asked about the project path, make sure to specify the `build` folder, for example:
2046 |
2047 | ```sh
2048 | project path: /path/to/project/build
2049 | ```
2050 |
2051 | Note that in order to support routers that use HTML5 `pushState` API, you may want to rename the `index.html` in your build folder to `200.html` before deploying to Surge. This [ensures that every URL falls back to that file](https://surge.sh/help/adding-a-200-page-for-client-side-routing).
2052 |
2053 | ## Advanced Configuration
2054 |
2055 | You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).
2056 |
2057 | Variable | Development | Production | Usage
2058 | :--- | :---: | :---: | :---
2059 | BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to `npm start` will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the `.js` extension.
2060 | HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host.
2061 | PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port.
2062 | HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode.
2063 | PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.
2064 | CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default.
2065 | REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebookincubator/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable points to your editor’s bin folder.
2066 | CHOKIDAR_USEPOLLING | :white_check_mark: | :x: | When set to `true`, the watcher runs in polling mode, as necessary inside a VM. Use this option if `npm start` isn't detecting changes.
2067 | GENERATE_SOURCEMAP | :x: | :white_check_mark: | When set to `false`, source maps are not generated for a production build. This solves OOM issues on some smaller machines.
2068 |
2069 | ## Troubleshooting
2070 |
2071 | ### `npm start` doesn’t detect changes
2072 |
2073 | When you save a file while `npm start` is running, the browser should refresh with the updated code.
2074 | If this doesn’t happen, try one of the following workarounds:
2075 |
2076 | * If your project is in a Dropbox folder, try moving it out.
2077 | * If the watcher doesn’t see a file called `index.js` and you’re referencing it by the folder name, you [need to restart the watcher](https://github.com/facebookincubator/create-react-app/issues/1164) due to a Webpack bug.
2078 | * Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in [“Adjusting Your Text Editor”](https://webpack.js.org/guides/development/#adjusting-your-text-editor).
2079 | * If your project path contains parentheses, try moving the project to a path without them. This is caused by a [Webpack watcher bug](https://github.com/webpack/watchpack/issues/42).
2080 | * On Linux and macOS, you might need to [tweak system settings](https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers) to allow more watchers.
2081 | * If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an `.env` file in your project directory if it doesn’t exist, and add `CHOKIDAR_USEPOLLING=true` to it. This ensures that the next time you run `npm start`, the watcher uses the polling mode, as necessary inside a VM.
2082 |
2083 | If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659).
2084 |
2085 | ### `npm test` hangs on macOS Sierra
2086 |
2087 | If you run `npm test` and the console gets stuck after printing `react-scripts test --env=jsdom` to the console there might be a problem with your [Watchman](https://facebook.github.io/watchman/) installation as described in [facebookincubator/create-react-app#713](https://github.com/facebookincubator/create-react-app/issues/713).
2088 |
2089 | We recommend deleting `node_modules` in your project and running `npm install` (or `yarn` if you use it) first. If it doesn't help, you can try one of the numerous workarounds mentioned in these issues:
2090 |
2091 | * [facebook/jest#1767](https://github.com/facebook/jest/issues/1767)
2092 | * [facebook/watchman#358](https://github.com/facebook/watchman/issues/358)
2093 | * [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259)
2094 |
2095 | It is reported that installing Watchman 4.7.0 or newer fixes the issue. If you use [Homebrew](http://brew.sh/), you can run these commands to update it:
2096 |
2097 | ```
2098 | watchman shutdown-server
2099 | brew update
2100 | brew reinstall watchman
2101 | ```
2102 |
2103 | You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page.
2104 |
2105 | If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
2106 |
2107 | There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
2108 |
2109 | ### `npm run build` exits too early
2110 |
2111 | It is reported that `npm run build` can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:
2112 |
2113 | > The build failed because the process exited too early. This probably means the system ran out of memory or someone called `kill -9` on the process.
2114 |
2115 | If you are completely sure that you didn't terminate the process, consider [adding some swap space](https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04) to the machine you’re building on, or build the project locally.
2116 |
2117 | ### `npm run build` fails on Heroku
2118 |
2119 | This may be a problem with case sensitive filenames.
2120 | Please refer to [this section](#resolving-heroku-deployment-errors).
2121 |
2122 | ### Moment.js locales are missing
2123 |
2124 | If you use a [Moment.js](https://momentjs.com/), you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of [all the locales provided by Moment.js](https://momentjs.com/#multiple-locale-support).
2125 |
2126 | To add a specific Moment.js locale to your bundle, you need to import it explicitly.
2127 | For example:
2128 |
2129 | ```js
2130 | import moment from 'moment';
2131 | import 'moment/locale/fr';
2132 | ```
2133 |
2134 | If import multiple locales this way, you can later switch between them by calling `moment.locale()` with the locale name:
2135 |
2136 | ```js
2137 | import moment from 'moment';
2138 | import 'moment/locale/fr';
2139 | import 'moment/locale/es';
2140 |
2141 | // ...
2142 |
2143 | moment.locale('fr');
2144 | ```
2145 |
2146 | This will only work for locales that have been explicitly imported before.
2147 |
2148 | ### `npm run build` fails to minify
2149 |
2150 | You may occasionally find a package you depend on needs compiled or ships code for a non-browser environment.
2151 | This is considered poor practice in the ecosystem and does not have an escape hatch in Create React App.
2152 |
2153 | To resolve this:
2154 | 1. Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled (retaining ES6 Modules).
2155 | 2. Fork the package and publish a corrected version yourself.
2156 | 3. If the dependency is small enough, copy it to your `src/` folder and treat it as application code.
2157 |
2158 | ## Something Missing?
2159 |
2160 | If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebookincubator/create-react-app/issues) or [contribute some!](https://github.com/facebookincubator/create-react-app/edit/master/packages/react-scripts/template/README.md)
2161 |
--------------------------------------------------------------------------------