├── docs
├── static
│ └── css
│ │ └── main.5518879a.css.map
├── asset-manifest.json
└── index.html
├── src
├── index.js
├── libs
│ ├── util.js
│ └── ajax.js
├── style.css
├── components
│ ├── Factory.jsx
│ ├── App.jsx
│ ├── FormModal.jsx
│ ├── Search.jsx
│ └── Content.jsx
├── api
│ └── sqlData.js
└── store
│ └── sqlConfig.js
├── .gitignore
├── config
├── jest
│ ├── fileTransform.js
│ └── cssTransform.js
├── polyfills.js
├── env.js
├── paths.js
├── webpack.config.dev.js
└── webpack.config.prod.js
├── scripts
├── test.js
├── build.js
└── start.js
├── public
└── index.html
├── README.md
├── package.json
└── README-CLI.md
/docs/static/css/main.5518879a.css.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":[],"names":[],"mappings":"","file":"static/css/main.5518879a.css","sourceRoot":""}
--------------------------------------------------------------------------------
/docs/asset-manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "main.css": "static/css/main.5518879a.css",
3 | "main.css.map": "static/css/main.5518879a.css.map",
4 | "main.js": "static/js/main.2a25180d.js",
5 | "main.js.map": "static/js/main.2a25180d.js.map"
6 | }
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import 'antd/dist/antd.css';
4 | import './style.css';
5 | import App from './components/App';
6 |
7 | ReactDOM.render( , document.getElementById('App'));
8 |
--------------------------------------------------------------------------------
/.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
15 | npm-debug.log*
16 | yarn-debug.log*
17 | yarn-error.log*
18 | .idea/
19 |
20 |
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
React CRUD | cnzsb
--------------------------------------------------------------------------------
/src/libs/util.js:
--------------------------------------------------------------------------------
1 | /* eslint import/prefer-default-export: 0 */
2 |
3 | /**
4 | * 对含有对象的数组,通过 key 和 value 筛选 index
5 | * @param key {String}
6 | * @param val {String | Number | Boolean}
7 | * @param arr {Array}
8 | * @return {Number}
9 | */
10 | export const findIndexByKey = (key, val, arr) => arr.findIndex(item => item[key] === val);
11 |
--------------------------------------------------------------------------------
/config/jest/fileTransform.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 |
3 | // This is a custom Jest transformer turning file imports into filenames.
4 | // http://facebook.github.io/jest/docs/tutorial-webpack.html
5 |
6 | module.exports = {
7 | process(src, filename) {
8 | return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
9 | },
10 | };
11 |
--------------------------------------------------------------------------------
/config/jest/cssTransform.js:
--------------------------------------------------------------------------------
1 | // This is a custom Jest transformer turning style imports into empty objects.
2 | // http://facebook.github.io/jest/docs/tutorial-webpack.html
3 |
4 | module.exports = {
5 | process() {
6 | return 'module.exports = {};';
7 | },
8 | getCacheKey(fileData, filename) {
9 | // The output is always the same.
10 | return 'cssTransform';
11 | },
12 | };
13 |
--------------------------------------------------------------------------------
/src/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | background-color: #f3f3f4;
3 | font-size: 14px;
4 | color: #676a6c;
5 | }
6 |
7 | .body {
8 | width: 960px;
9 | margin: 0 auto;
10 | }
11 |
12 | /* Fix ButtonGroup's borderRightColor */
13 | .ant-btn-group .ant-btn-primary:last-child:not(:first-child)[disabled],
14 | .ant-btn-group .ant-btn-primary + .ant-btn[disabled] {
15 | border-right-color: #d9d9d9;
16 | }
17 |
--------------------------------------------------------------------------------
/src/libs/ajax.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 | import { notification } from 'antd';
3 |
4 | const $http = axios.create({});
5 |
6 | // response
7 | $http.interceptors.response.use(
8 | ({ data: { data } }) => data,
9 | ({ response }) => {
10 | notification.error({
11 | message: '错误',
12 | description: '请求错误,请稍后再试',
13 | });
14 | return Promise.reject(response);
15 | },
16 | );
17 |
18 | export default $http;
19 |
--------------------------------------------------------------------------------
/scripts/test.js:
--------------------------------------------------------------------------------
1 | process.env.NODE_ENV = 'test';
2 | process.env.PUBLIC_URL = '';
3 |
4 | // Load environment variables from .env file. Suppress warnings using silent
5 | // if this file is missing. dotenv will never modify any environment variables
6 | // that have already been set.
7 | // https://github.com/motdotla/dotenv
8 | require('dotenv').config({silent: true});
9 |
10 | const jest = require('jest');
11 | const argv = process.argv.slice(2);
12 |
13 | // Watch unless on CI or in coverage mode
14 | if (!process.env.CI && argv.indexOf('--coverage') < 0) {
15 | argv.push('--watch');
16 | }
17 |
18 |
19 | jest.run(argv);
20 |
--------------------------------------------------------------------------------
/config/polyfills.js:
--------------------------------------------------------------------------------
1 | if (typeof Promise === 'undefined') {
2 | // Rejection tracking prevents a common issue where React gets into an
3 | // inconsistent state due to an error, but it gets swallowed by a Promise,
4 | // and the user has no idea what causes React's erratic future behavior.
5 | require('promise/lib/rejection-tracking').enable();
6 | window.Promise = require('promise/lib/es6-extensions.js');
7 | }
8 |
9 | // fetch() polyfill for making API calls.
10 | require('whatwg-fetch');
11 |
12 | // Object.assign() is commonly used with React.
13 | // It will use the native implementation if it's present and isn't buggy.
14 | Object.assign = require('object-assign');
15 |
--------------------------------------------------------------------------------
/src/components/Factory.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Input } from 'antd';
3 |
4 | export default class Factory extends React.Component {
5 | render() {
6 | const { type, target, keyName, onChange } = this.props;
7 | switch (type) {
8 | case 'text':
9 | return onChange(e, keyName)} />;
10 | case 'display':
11 | return !target[keyName] ? : (
12 | {target[keyName]}
13 | );
14 | default:
15 | return null;
16 | }
17 | }
18 | }
19 |
20 | Factory.propTypes = {
21 | type: React.PropTypes.string,
22 | target: React.PropTypes.objectOf(React.PropTypes.shape),
23 | keyName: React.PropTypes.string,
24 | onChange: React.PropTypes.func,
25 | };
26 |
--------------------------------------------------------------------------------
/src/api/sqlData.js:
--------------------------------------------------------------------------------
1 | import $http from '../libs/ajax';
2 |
3 | export const getTableUsers = params => {
4 | /* return $http.get('api/users', params)
5 | .then(data => Promise.resolve(data)) */
6 | // 模拟数据
7 | const data = [];
8 | // Create 1000 users
9 | for (let i = 1; i < 1000; i++) {
10 | data.push({
11 | id: i,
12 | name: 'user' + i,
13 | sex: Math.random().toString().substr(2, 1) % 2 === 0 ? 'male' : 'female',
14 | age: 2 + Math.random().toString().substr(2, 1),
15 | remark: 'I have got ' + Math.random().toString().substr(2, 4) + ' coins'
16 | });
17 | }
18 | return Promise.resolve(data);
19 | };
20 |
21 | // todo 表单 Users 的 ajax
22 | export const getTableNone = params => (
23 | $http.get('api/pageWhichIsNo', params)
24 | .then(data => Promise.resolve(data))
25 | );
26 |
27 | export default {
28 | getTableUsers,
29 | getTableNone,
30 | };
31 |
32 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
15 | React CRUD | cnzsb
16 |
17 |
18 |
19 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/src/components/App.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Menu } from 'antd';
3 | import Content from './Content';
4 | import sqlData from '../store/sqlConfig';
5 |
6 | const MenuItem = Menu.Item;
7 |
8 | export default class App extends React.Component {
9 | constructor() {
10 | super();
11 | this.state = {
12 | tableName: 'Users',
13 | };
14 |
15 | this.openTable = this.openTable.bind(this);
16 | }
17 |
18 | openTable({ key }) {
19 | this.setState({
20 | tableName: key,
21 | });
22 | }
23 |
24 | render() {
25 | return (
26 |
27 |
React CRUD
28 |
34 | {
35 | sqlData.map(data => (
36 |
37 | {data.name}
38 |
39 | ))
40 | }
41 |
42 |
43 |
44 | );
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/config/env.js:
--------------------------------------------------------------------------------
1 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
2 | // injected into the application via DefinePlugin in Webpack configuration.
3 |
4 | var REACT_APP = /^REACT_APP_/i;
5 |
6 | function getClientEnvironment(publicUrl) {
7 | var raw = Object
8 | .keys(process.env)
9 | .filter(key => REACT_APP.test(key))
10 | .reduce((env, key) => {
11 | env[key] = process.env[key];
12 | return env;
13 | }, {
14 | // Useful for determining whether we’re running in production mode.
15 | // Most importantly, it switches React into the correct mode.
16 | 'NODE_ENV': process.env.NODE_ENV || 'development',
17 | // Useful for resolving the correct path to static assets in `public`.
18 | // For example, .
19 | // This should only be used as an escape hatch. Normally you would put
20 | // images into the `src` and `import` them in code to get their paths.
21 | 'PUBLIC_URL': publicUrl
22 | });
23 | // Stringify all values so we can feed into Webpack DefinePlugin
24 | var stringified = {
25 | 'process.env': Object
26 | .keys(raw)
27 | .reduce((env, key) => {
28 | env[key] = JSON.stringify(raw[key]);
29 | return env;
30 | }, {})
31 | };
32 |
33 | return { raw, stringified };
34 | }
35 |
36 | module.exports = getClientEnvironment;
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## React-antd-CRUD
2 |
3 | 本项目是基于 react 和 antd 的 CRUD 应用。
4 |
5 | ### 开始
6 |
7 | 项目使用官方脚手架 [create-react-app](https://github.com/facebookincubator/create-react-app) 搭建,相关指令同理。
8 |
9 | ### 说明
10 |
11 | 本项目详细说明参看[博客](http://www.zhaoshibo.net/blog/2017/03/09/%E4%BB%8E%E4%B8%80%E4%B8%AA%20CRUD%20%E4%B8%8A%E6%89%8B%20React%20%E5%92%8C%20AntD/)。
12 |
13 | 主要目录结构:
14 |
15 | ```bash
16 | |-- api
17 | | |-- sqlData.js # 操作 sqlData 的 ajax 方法
18 | |-- components
19 | | |-- App.jsx # 页面
20 | | |-- Content.jsx # 页面主体内容区
21 | | |-- Factory.jsx # 表单组件工厂
22 | | |-- FormModal.jsx # 弹出的增加或编辑的表单组件
23 | | |-- Search.jsx # 搜索组件
24 | |-- libs
25 | | |-- ajax.js # ajax 实例及公共方法
26 | | |-- util.js # 工具方法
27 | |-- store
28 | | |-- sqlConfig.js # 数据库表单配置项
29 | |-- index.js # 入口文件
30 | |-- style.css # 样式文件
31 | ```
32 |
33 | 主要组件结构:
34 |
35 | ```bash
36 | |-- App
37 | | |-- Menu # 导航菜单
38 | | |-- Content # 主要内容区
39 | | |-- Search # 搜索组件
40 | | |-- Factory # 表单工厂
41 | | |-- ButtonGroup # 操作按钮群
42 | | |-- Table # 表格组件
43 | | |-- Pagination # 分页组件
44 | | |-- FormModal # 弹出的编辑表单
45 | | |-- Factory # 表单工厂
46 | ```
47 |
48 | 组件结构图解:
49 |
50 | 
--------------------------------------------------------------------------------
/src/store/sqlConfig.js:
--------------------------------------------------------------------------------
1 | export default [
2 | {
3 | tableName: 'Users',
4 | name: '用户信息',
5 | headers: [
6 | {
7 | tableKey: 'id',
8 | name: 'ID',
9 | type: 'display',
10 | width: 50,
11 | },
12 | {
13 | tableKey: 'name',
14 | name: '姓名',
15 | type: 'text',
16 | width: 80,
17 | validators: [
18 | 'required',
19 | ],
20 | },
21 | {
22 | tableKey: 'sex',
23 | name: '性别',
24 | type: 'text',
25 | width: 50,
26 | },
27 | {
28 | tableKey: 'age',
29 | name: '年龄',
30 | type: 'text',
31 | width: 50,
32 | validators: [
33 | 'required',
34 | ],
35 | },
36 | {
37 | tableKey: 'remark',
38 | name: '备注',
39 | type: 'text',
40 | width: 150,
41 | validators: [
42 | 'required',
43 | ],
44 | },
45 | ],
46 | },
47 | {
48 | tableName: 'None',
49 | name: '异常模拟',
50 | headers: [
51 | {
52 | tableKey: 'id',
53 | name: 'id',
54 | type: 'display',
55 | width: 50,
56 | },
57 | {
58 | tableKey: 'name',
59 | name: '姓名',
60 | type: 'text',
61 | width: 80,
62 | validators: [
63 | 'required',
64 | ],
65 | },
66 | {
67 | tableKey: 'comment',
68 | name: '评论',
69 | type: 'text',
70 | width: 200,
71 | validators: [
72 | '',
73 | ],
74 | },
75 | {
76 | tableKey: 'status',
77 | name: '状态',
78 | type: 'text',
79 | width: 50,
80 | validators: [
81 | 'required',
82 | ],
83 | },
84 | ],
85 | }];
86 |
--------------------------------------------------------------------------------
/src/components/FormModal.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Modal, Form } from 'antd';
3 | import Factory from './Factory';
4 |
5 | const FormItem = Form.Item;
6 |
7 | export default class FormModal extends React.Component {
8 | constructor() {
9 | super();
10 |
11 | this.state = {};
12 | }
13 |
14 | render() {
15 | const {
16 | formModalTitle,
17 | formConfigs,
18 | formValues,
19 | showFormModal,
20 | submitFormModal,
21 | cancelFormModal,
22 | confirmLoading,
23 | onChange,
24 | } = this.props;
25 |
26 | return (
27 |
34 |
50 |
51 | );
52 | }
53 | }
54 |
55 | FormModal.propTypes = {
56 | formModalTitle: React.PropTypes.string,
57 | formConfigs: React.PropTypes.arrayOf(React.PropTypes.shape),
58 | formValues: React.PropTypes.objectOf(React.PropTypes.shape),
59 | onChange: React.PropTypes.objectOf(React.PropTypes.shape),
60 | showFormModal: React.PropTypes.bool,
61 | submitFormModal: React.PropTypes.func,
62 | cancelFormModal: React.PropTypes.func,
63 | confirmLoading: React.PropTypes.bool,
64 | };
65 |
--------------------------------------------------------------------------------
/src/components/Search.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Row, Col, Form, Button, Icon } from 'antd';
3 | import Factory from './Factory';
4 |
5 | const FormItem = Form.Item;
6 |
7 | export default class Search extends React.Component {
8 | constructor() {
9 | super();
10 |
11 | this.state = {};
12 | }
13 |
14 | render() {
15 | const { configs, values, onChange, submitSearch, resetSearch } = this.props;
16 |
17 | return (
18 |
19 |
41 |
42 |
43 |
44 |
45 | 重置
46 |
47 |
48 |
49 | 搜索
50 |
51 |
52 |
53 | );
54 | }
55 | }
56 |
57 | Search.propTypes = {
58 | configs: React.PropTypes.arrayOf(React.PropTypes.shape),
59 | values: React.PropTypes.objectOf(React.PropTypes.shape),
60 | onChange: React.PropTypes.objectOf(React.PropTypes.shape),
61 | submitSearch: React.PropTypes.func,
62 | resetSearch: React.PropTypes.func,
63 | };
64 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-antd-crud",
3 | "version": "0.1.0",
4 | "private": true,
5 | "devDependencies": {
6 | "autoprefixer": "6.7.2",
7 | "babel-core": "6.22.1",
8 | "babel-eslint": "7.1.1",
9 | "babel-jest": "18.0.0",
10 | "babel-loader": "6.2.10",
11 | "babel-plugin-import": "1.1.1",
12 | "babel-preset-react-app": "^2.1.1",
13 | "babel-runtime": "^6.20.0",
14 | "case-sensitive-paths-webpack-plugin": "1.1.4",
15 | "chalk": "1.1.3",
16 | "connect-history-api-fallback": "1.3.0",
17 | "cross-spawn": "4.0.2",
18 | "css-loader": "0.26.1",
19 | "detect-port": "1.0.1",
20 | "dotenv": "2.0.0",
21 | "eslint": "3.8.1",
22 | "eslint-config-react-app": "^0.5.2",
23 | "eslint-loader": "1.6.0",
24 | "eslint-plugin-flowtype": "2.21.0",
25 | "eslint-plugin-import": "2.0.1",
26 | "eslint-plugin-jsx-a11y": "2.2.3",
27 | "eslint-plugin-react": "6.4.1",
28 | "extract-text-webpack-plugin": "1.0.1",
29 | "file-loader": "0.10.0",
30 | "filesize": "3.3.0",
31 | "fs-extra": "0.30.0",
32 | "gzip-size": "3.0.0",
33 | "html-webpack-plugin": "2.24.0",
34 | "http-proxy-middleware": "0.17.3",
35 | "jest": "18.1.0",
36 | "json-loader": "0.5.4",
37 | "object-assign": "4.1.1",
38 | "postcss-loader": "1.2.2",
39 | "promise": "7.1.1",
40 | "react-dev-utils": "^0.5.1",
41 | "recursive-readdir": "2.1.1",
42 | "strip-ansi": "3.0.1",
43 | "style-loader": "0.13.1",
44 | "url-loader": "0.5.7",
45 | "webpack": "1.14.0",
46 | "webpack-dev-server": "1.16.2",
47 | "webpack-manifest-plugin": "1.1.0",
48 | "whatwg-fetch": "2.0.2"
49 | },
50 | "dependencies": {
51 | "antd": "2.7.4",
52 | "axios": "0.15.3",
53 | "react": "15.4.2",
54 | "react-dom": "15.4.2"
55 | },
56 | "scripts": {
57 | "start": "node scripts/start.js",
58 | "build": "node scripts/build.js",
59 | "test": "node scripts/test.js --env=jsdom"
60 | },
61 | "jest": {
62 | "collectCoverageFrom": [
63 | "src/**/*.{js,jsx}"
64 | ],
65 | "setupFiles": [
66 | "/config/polyfills.js"
67 | ],
68 | "testPathIgnorePatterns": [
69 | "[/\\\\](build|docs|node_modules|scripts)[/\\\\]"
70 | ],
71 | "testEnvironment": "node",
72 | "testURL": "http://localhost",
73 | "transform": {
74 | "^.+\\.(js|jsx)$": "/node_modules/babel-jest",
75 | "^.+\\.css$": "/config/jest/cssTransform.js",
76 | "^(?!.*\\.(js|jsx|css|json)$)": "/config/jest/fileTransform.js"
77 | },
78 | "transformIgnorePatterns": [
79 | "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
80 | ],
81 | "moduleNameMapper": {
82 | "^react-native$": "react-native-web"
83 | }
84 | },
85 | "babel": {
86 | "presets": [
87 | "react-app"
88 | ]
89 | },
90 | "eslintConfig": {
91 | "extends": "react-app"
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/config/paths.js:
--------------------------------------------------------------------------------
1 | var path = require('path');
2 | var fs = require('fs');
3 | var url = require('url');
4 |
5 | // Make sure any symlinks in the project folder are resolved:
6 | // https://github.com/facebookincubator/create-react-app/issues/637
7 | var appDirectory = fs.realpathSync(process.cwd());
8 | function resolveApp(relativePath) {
9 | return path.resolve(appDirectory, relativePath);
10 | }
11 |
12 | // We support resolving modules according to `NODE_PATH`.
13 | // This lets you use absolute paths in imports inside large monorepos:
14 | // https://github.com/facebookincubator/create-react-app/issues/253.
15 |
16 | // It works similar to `NODE_PATH` in Node itself:
17 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
18 |
19 | // We will export `nodePaths` as an array of absolute paths.
20 | // It will then be used by Webpack configs.
21 | // Jest doesn’t need this because it already handles `NODE_PATH` out of the box.
22 |
23 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
24 | // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
25 | // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
26 |
27 | var nodePaths = (process.env.NODE_PATH || '')
28 | .split(process.platform === 'win32' ? ';' : ':')
29 | .filter(Boolean)
30 | .filter(folder => !path.isAbsolute(folder))
31 | .map(resolveApp);
32 |
33 | var envPublicUrl = process.env.PUBLIC_URL;
34 |
35 | function ensureSlash(path, needsSlash) {
36 | var hasSlash = path.endsWith('/');
37 | if (hasSlash && !needsSlash) {
38 | return path.substr(path, path.length - 1);
39 | } else if (!hasSlash && needsSlash) {
40 | return path + '/';
41 | } else {
42 | return path;
43 | }
44 | }
45 |
46 | function getPublicUrl(appPackageJson) {
47 | return envPublicUrl || require(appPackageJson).homepage;
48 | }
49 |
50 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer
51 | // "public path" at which the app is served.
52 | // Webpack needs to know it to put the right
886 | ```
887 |
888 | 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.**
889 |
890 | ## Running Tests
891 |
892 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
893 | >[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)
894 |
895 | 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.
896 |
897 | 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.
898 |
899 | 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.
900 |
901 | 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.
902 |
903 | ### Filename Conventions
904 |
905 | Jest will look for test files with any of the following popular naming conventions:
906 |
907 | * Files with `.js` suffix in `__tests__` folders.
908 | * Files with `.test.js` suffix.
909 | * Files with `.spec.js` suffix.
910 |
911 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder.
912 |
913 | 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.jsx` and `App.jsx` 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.
914 |
915 | ### Command Line Interface
916 |
917 | 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.
918 |
919 | 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:
920 |
921 | 
922 |
923 | ### Version Control Integration
924 |
925 | 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 runs 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.
926 |
927 | 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.
928 |
929 | 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.
930 |
931 | ### Writing Tests
932 |
933 | 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.
934 |
935 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
936 |
937 | ```js
938 | import sum from './sum';
939 |
940 | it('sums numbers', () => {
941 | expect(sum(1, 2)).toEqual(3);
942 | expect(sum(2, 2)).toEqual(4);
943 | });
944 | ```
945 |
946 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
947 | 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.
948 |
949 | ### Testing Components
950 |
951 | 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.
952 |
953 | 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:
954 |
955 | ```js
956 | import React from 'react';
957 | import ReactDOM from 'react-dom';
958 | import App from './App';
959 |
960 | it('renders without crashing', () => {
961 | const div = document.createElement('div');
962 | ReactDOM.render( , div);
963 | });
964 | ```
965 |
966 | 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.jsx`.
967 |
968 | 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.
969 |
970 | 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/). You can write a smoke test with it too:
971 |
972 | ```sh
973 | npm install --save-dev enzyme react-addons-test-utils
974 | ```
975 |
976 | ```js
977 | import React from 'react';
978 | import { shallow } from 'enzyme';
979 | import App from './App';
980 |
981 | it('renders without crashing', () => {
982 | shallow( );
983 | });
984 | ```
985 |
986 | 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.
987 |
988 | 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.
989 |
990 | Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
991 |
992 | ```js
993 | import React from 'react';
994 | import { shallow } from 'enzyme';
995 | import App from './App';
996 |
997 | it('renders welcome message', () => {
998 | const wrapper = shallow( );
999 | const welcome = Welcome to React ;
1000 | // expect(wrapper.contains(welcome)).to.equal(true);
1001 | expect(wrapper.contains(welcome)).toEqual(true);
1002 | });
1003 | ```
1004 |
1005 | All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1006 | Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below.
1007 |
1008 | 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.
1009 |
1010 | ```js
1011 | expect(wrapper).toContainReact(welcome)
1012 | ```
1013 |
1014 | To setup jest-enzyme with Create React App, follow the instructions for [initializing your test environment](#initializing-test-environment) to import `jest-enzyme`.
1015 |
1016 | ```sh
1017 | npm install --save-dev jest-enzyme
1018 | ```
1019 |
1020 | ```js
1021 | // src/setupTests.js
1022 | import 'jest-enzyme';
1023 | ```
1024 |
1025 |
1026 | ### Using Third Party Assertion Libraries
1027 |
1028 | 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).
1029 |
1030 | 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:
1031 |
1032 | ```js
1033 | import sinon from 'sinon';
1034 | import { expect } from 'chai';
1035 | ```
1036 |
1037 | and then use them in your tests like you normally do.
1038 |
1039 | ### Initializing Test Environment
1040 |
1041 | >Note: this feature is available with `react-scripts@0.4.0` and higher.
1042 |
1043 | 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.
1044 |
1045 | For example:
1046 |
1047 | #### `src/setupTests.js`
1048 | ```js
1049 | const localStorageMock = {
1050 | getItem: jest.fn(),
1051 | setItem: jest.fn(),
1052 | clear: jest.fn()
1053 | };
1054 | global.localStorage = localStorageMock
1055 | ```
1056 |
1057 | ### Focusing and Excluding Tests
1058 |
1059 | You can replace `it()` with `xit()` to temporarily exclude a test from being executed.
1060 | Similarly, `fit()` lets you focus on a specific test without running any other tests.
1061 |
1062 | ### Coverage Reporting
1063 |
1064 | Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.
1065 | Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this:
1066 |
1067 | 
1068 |
1069 | Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow.
1070 |
1071 | ### Continuous Integration
1072 |
1073 | 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`.
1074 |
1075 | 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.
1076 |
1077 | Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
1078 |
1079 | ### On CI servers
1080 | #### Travis CI
1081 |
1082 | 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.
1083 | 1. Add a `.travis.yml` file to your git repository.
1084 | ```
1085 | language: node_js
1086 | node_js:
1087 | - 4
1088 | - 6
1089 | cache:
1090 | directories:
1091 | - node_modules
1092 | script:
1093 | - npm test
1094 | - npm run build
1095 | ```
1096 | 1. Trigger your first build with a git push.
1097 | 1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
1098 |
1099 | ### On your own environment
1100 | ##### Windows (cmd.exe)
1101 |
1102 | ```cmd
1103 | set CI=true&&npm test
1104 | ```
1105 |
1106 | ```cmd
1107 | set CI=true&&npm run build
1108 | ```
1109 |
1110 | (Note: the lack of whitespace is intentional.)
1111 |
1112 | ##### Linux, macOS (Bash)
1113 |
1114 | ```bash
1115 | CI=true npm test
1116 | ```
1117 |
1118 | ```bash
1119 | CI=true npm run build
1120 | ```
1121 |
1122 | The test command will force Jest to run tests once instead of launching the watcher.
1123 |
1124 | > 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.
1125 |
1126 | The build command will check for linter warnings and fail if any are found.
1127 |
1128 | ### Disabling jsdom
1129 |
1130 | By default, the `package.json` of the generated project looks like this:
1131 |
1132 | ```js
1133 | // ...
1134 | "scripts": {
1135 | // ...
1136 | "test": "react-scripts test --env=jsdom"
1137 | }
1138 | ```
1139 |
1140 | 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.
1141 | To help you make up your mind, here is a list of APIs that **need jsdom**:
1142 |
1143 | * Any browser globals like `window` and `document`
1144 | * [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render)
1145 | * [`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)
1146 | * [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1147 |
1148 | In contrast, **jsdom is not needed** for the following APIs:
1149 |
1150 | * [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering)
1151 | * [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1152 |
1153 | Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html).
1154 |
1155 | ### Snapshot Testing
1156 |
1157 | 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)
1158 |
1159 | ### Editor Integration
1160 |
1161 | 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.
1162 |
1163 | 
1164 |
1165 | ## Developing Components in Isolation
1166 |
1167 | Usually, in an app, you have a lot of UI components, and each of them has many different states.
1168 | For an example, a simple button component could have following states:
1169 |
1170 | * With a text label.
1171 | * With an emoji.
1172 | * In the disabled mode.
1173 |
1174 | Usually, it’s hard to see these states without running a sample app or some examples.
1175 |
1176 | Create React App doesn’t include any tools for this by default, but you can easily add [React Storybook](https://github.com/kadirahq/react-storybook) to your project. **It is a third-party tool that lets you develop components and see all their states in isolation from your app**.
1177 |
1178 | 
1179 |
1180 | You can also deploy your Storybook 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.
1181 |
1182 | **Here’s how to setup your app with Storybook:**
1183 |
1184 | First, install the following npm package globally:
1185 |
1186 | ```sh
1187 | npm install -g getstorybook
1188 | ```
1189 |
1190 | Then, run the following command inside your app’s directory:
1191 |
1192 | ```sh
1193 | getstorybook
1194 | ```
1195 |
1196 | After that, follow the instructions on the screen.
1197 |
1198 | Learn more about React Storybook:
1199 |
1200 | * Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook)
1201 | * [GitHub Repo](https://github.com/kadirahq/react-storybook)
1202 | * [Documentation](https://getstorybook.io/docs)
1203 | * [Snapshot Testing](https://github.com/kadirahq/storyshots) with React Storybook
1204 |
1205 | ## Making a Progressive Web App
1206 |
1207 | You can turn your React app into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) by following the steps in [this repository](https://github.com/jeffposnick/create-react-pwa).
1208 |
1209 | ## Deployment
1210 |
1211 | `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. For example, Python contains a built-in HTTP server that can serve static files:
1212 |
1213 | ```sh
1214 | cd build
1215 | python -m SimpleHTTPServer 9000
1216 | ```
1217 |
1218 | If you’re using [Node](https://nodejs.org/) and [Express](http://expressjs.com/) as a server, it might look like this:
1219 |
1220 | ```javascript
1221 | const express = require('express');
1222 | const path = require('path');
1223 | const app = express();
1224 |
1225 | app.use(express.static('./build'));
1226 |
1227 | app.get('/', function (req, res) {
1228 | res.sendFile(path.join(__dirname, './build', 'index.html'));
1229 | });
1230 |
1231 | app.listen(9000);
1232 | ```
1233 |
1234 | Create React App is not opinionated about your choice of web server. Any static file server will do. The `build` folder with static assets is the only output produced by Create React App.
1235 |
1236 | 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.
1237 |
1238 | ### Serving Apps with Client-Side Routing
1239 |
1240 | 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.
1241 |
1242 | 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:
1243 |
1244 | ```diff
1245 | app.use(express.static('./build'));
1246 |
1247 | -app.get('/', function (req, res) {
1248 | +app.get('/*', function (req, res) {
1249 | res.sendFile(path.join(__dirname, './build', 'index.html'));
1250 | });
1251 | ```
1252 |
1253 | Now requests to `/todos/42` will be handled correctly both in development and in production.
1254 |
1255 | ### Building for Relative Paths
1256 |
1257 | By default, Create React App produces a build assuming your app is hosted at the server root.
1258 | To override this, specify the `homepage` in your `package.json`, for example:
1259 |
1260 | ```js
1261 | "homepage": "http://mywebsite.com/relativepath",
1262 | ```
1263 |
1264 | This will let Create React App correctly infer the root path to use in the generated HTML file.
1265 |
1266 | #### Serving the Same Build from Different Paths
1267 |
1268 | >Note: this feature is available with `react-scripts@0.9.0` and higher.
1269 |
1270 | 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`:
1271 |
1272 | ```js
1273 | "homepage": ".",
1274 | ```
1275 |
1276 | 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.
1277 |
1278 | ### Azure
1279 |
1280 | 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/).
1281 |
1282 | ### Firebase
1283 |
1284 | 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.
1285 |
1286 | 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`.
1287 |
1288 | ```sh
1289 | === Project Setup
1290 |
1291 | First, let's associate this project directory with a Firebase project.
1292 | You can create multiple project aliases by running firebase use --add,
1293 | but for now we'll just set up a default project.
1294 |
1295 | ? What Firebase project do you want to associate as default? Example app (example-app-fd690)
1296 |
1297 | === Database Setup
1298 |
1299 | Firebase Realtime Database Rules allow you to define how your data should be
1300 | structured and when your data can be read from and written to.
1301 |
1302 | ? What file should be used for Database Rules? database.rules.json
1303 | ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json.
1304 | Future modifications to database.rules.json will update Database Rules when you run
1305 | firebase deploy.
1306 |
1307 | === Hosting Setup
1308 |
1309 | Your public directory is the folder (relative to your project directory) that
1310 | will contain Hosting assets to uploaded with firebase deploy. If you
1311 | have a build process for your assets, use your build's output directory.
1312 |
1313 | ? What do you want to use as your public directory? build
1314 | ? Configure as a single-page app (rewrite all urls to /index.html)? Yes
1315 | ✔ Wrote build/index.html
1316 |
1317 | i Writing configuration info to firebase.json...
1318 | i Writing project information to .firebaserc...
1319 |
1320 | ✔ Firebase initialization complete!
1321 | ```
1322 |
1323 | Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`.
1324 |
1325 | ```sh
1326 | === Deploying to 'example-app-fd690'...
1327 |
1328 | i deploying database, hosting
1329 | ✔ database: rules ready to deploy.
1330 | i hosting: preparing build directory for upload...
1331 | Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully
1332 | ✔ hosting: 8 files uploaded successfully
1333 | i starting release process (may take several minutes)...
1334 |
1335 | ✔ Deploy complete!
1336 |
1337 | Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
1338 | Hosting URL: https://example-app-fd690.firebaseapp.com
1339 | ```
1340 |
1341 | For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup).
1342 |
1343 | ### GitHub Pages
1344 |
1345 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
1346 |
1347 | #### Step 1: Add `homepage` to `package.json`
1348 |
1349 | **The step below is important!**
1350 | **If you skip it, your app will not deploy correctly.**
1351 |
1352 | Open your `package.json` and add a `homepage` field:
1353 |
1354 | ```js
1355 | "homepage": "https://myusername.github.io/my-app",
1356 | ```
1357 |
1358 | Create React App uses the `homepage` field to determine the root URL in the built HTML file.
1359 |
1360 | #### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`
1361 |
1362 | Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
1363 |
1364 | To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run:
1365 |
1366 | ```sh
1367 | npm install --save-dev gh-pages
1368 | ```
1369 |
1370 | Add the following scripts in your `package.json`:
1371 |
1372 | ```js
1373 | // ...
1374 | "scripts": {
1375 | // ...
1376 | "predeploy": "npm run build",
1377 | "deploy": "gh-pages -d build"
1378 | }
1379 | ```
1380 |
1381 | The `predeploy` script will run automatically before `deploy` is run.
1382 |
1383 | #### Step 3: Deploy the site by running `npm run deploy`
1384 |
1385 | Then run:
1386 |
1387 | ```sh
1388 | npm run deploy
1389 | ```
1390 |
1391 | #### Step 4: Ensure your project’s settings use `gh-pages`
1392 |
1393 | Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch:
1394 |
1395 |
1396 |
1397 | #### Step 5: Optionally, configure the domain
1398 |
1399 | You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder.
1400 |
1401 | #### Notes on client-side routing
1402 |
1403 | 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:
1404 |
1405 | * 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://github.com/reactjs/react-router/blob/master/docs/guides/Histories.md#histories) about different history implementations in React Router.
1406 | * 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).
1407 |
1408 | ### Heroku
1409 |
1410 | Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).
1411 | You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration).
1412 |
1413 | #### Resolving Heroku Deployment Errors
1414 |
1415 | Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases.
1416 |
1417 | ##### "Module not found: Error: Cannot resolve 'file' or 'directory'"
1418 |
1419 | If you get something like this:
1420 |
1421 | ```
1422 | remote: Failed to create a production build. Reason:
1423 | remote: Module not found: Error: Cannot resolve 'file' or 'directory'
1424 | MyDirectory in /tmp/build_1234/src
1425 | ```
1426 |
1427 | 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.
1428 |
1429 | 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.
1430 |
1431 | ##### "Could not find a required file."
1432 |
1433 | If you exclude or ignore necessary files from the package you will see a error similar this one:
1434 |
1435 | ```
1436 | remote: Could not find a required file.
1437 | remote: Name: `index.html`
1438 | remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public
1439 | remote:
1440 | remote: npm ERR! Linux 3.13.0-105-generic
1441 | remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build"
1442 | ```
1443 |
1444 | 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`.
1445 |
1446 | ### Modulus
1447 |
1448 | See the [Modulus blog post](http://blog.modulus.io/deploying-react-apps-on-modulus) on how to deploy your react app to Modulus.
1449 |
1450 | ## Netlify
1451 |
1452 | **To do a manual deploy to Netlify’s CDN:**
1453 |
1454 | ```sh
1455 | npm install netlify-cli
1456 | netlify deploy
1457 | ```
1458 |
1459 | Choose `build` as the path to deploy.
1460 |
1461 | **To setup continuous delivery:**
1462 |
1463 | With this setup Netlify will build and deploy when you push to git or open a pull request:
1464 |
1465 | 1. [Start a new netlify project](https://app.netlify.com/signup)
1466 | 2. Pick your Git hosting service and select your repository
1467 | 3. Click `Build your site`
1468 |
1469 | **Support for client-side routing:**
1470 |
1471 | To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules:
1472 |
1473 | ```
1474 | /* /index.html 200
1475 | ```
1476 |
1477 | When you build the project, Create React App will place the `public` folder contents into the build output.
1478 |
1479 | ### Now
1480 |
1481 | See [this example](https://github.com/xkawi/create-react-app-now) for a zero-configuration single-command deployment with [now](https://zeit.co/now).
1482 |
1483 | ### S3 and CloudFront
1484 |
1485 | 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/).
1486 |
1487 | ### Surge
1488 |
1489 | 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. You just need to specify the *build* folder and your custom domain, and you are done.
1490 |
1491 | ```sh
1492 | email: email@domain.com
1493 | password: ********
1494 | project path: /path/to/project/build
1495 | size: 7 files, 1.8 MB
1496 | domain: create-react-app.surge.sh
1497 | upload: [====================] 100%, eta: 0.0s
1498 | propagate on CDN: [====================] 100%
1499 | plan: Free
1500 | users: email@domain.com
1501 | IP Address: X.X.X.X
1502 |
1503 | Success! Project is published and running at create-react-app.surge.sh
1504 | ```
1505 |
1506 | 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).
1507 |
1508 | ## Advanced Configuration
1509 |
1510 | You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).
1511 |
1512 | Variable | Development | Production | Usage
1513 | :--- | :---: | :---: | :---
1514 | 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.
1515 | HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host.
1516 | 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.
1517 | HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode.
1518 | 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.
1519 | 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.
1520 |
1521 | ## Troubleshooting
1522 |
1523 | ### `npm start` doesn’t detect changes
1524 |
1525 | When you save a file while `npm start` is running, the browser should refresh with the updated code.
1526 | If this doesn’t happen, try one of the following workarounds:
1527 |
1528 | * If your project is in a Dropbox folder, try moving it out.
1529 | * 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.
1530 | * 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 [“Working with editors supporting safe write”](https://webpack.github.io/docs/webpack-dev-server.html#working-with-editors-ides-supporting-safe-write).
1531 | * 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).
1532 | * 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.
1533 | * If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, run `npm install --save-dev cross-env` in its root folder and then replace `"react-scripts start"` in the `scripts` section of its `package.json` with `"cross-env CHOKIDAR_USEPOLLING=true react-scripts start"`. This ensures that the next time you run `npm start`, the watcher uses the polling mode, as necessary inside a VM.
1534 |
1535 | If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659).
1536 |
1537 | ### `npm test` hangs on macOS Sierra
1538 |
1539 | 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).
1540 |
1541 | 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:
1542 |
1543 | * [facebook/jest#1767](https://github.com/facebook/jest/issues/1767)
1544 | * [facebook/watchman#358](https://github.com/facebook/watchman/issues/358)
1545 | * [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259)
1546 |
1547 | 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:
1548 |
1549 | ```
1550 | watchman shutdown-server
1551 | brew update
1552 | brew reinstall watchman
1553 | ```
1554 |
1555 | You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page.
1556 |
1557 | If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
1558 |
1559 | There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
1560 |
1561 | ### `npm run build` silently fails
1562 |
1563 | It is reported that `npm run build` can fail on machines with no swap space, which is common in cloud environments. If [the symptoms are matching](https://github.com/facebookincubator/create-react-app/issues/1133#issuecomment-264612171), consider adding some swap space to the machine you’re building on, or build the project locally.
1564 |
1565 | ### `npm run build` fails on Heroku
1566 |
1567 | This may be a problem with case sensitive filenames.
1568 | Please refer to [this section](#resolving-heroku-deployment-errors).
1569 |
1570 | ## Something Missing?
1571 |
1572 | 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)
1573 |
--------------------------------------------------------------------------------