README.md 79.7 KB
Newer Older
Dan Abramov's avatar
Dan Abramov committed
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
```js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';

it('renders welcome message', () => {
  const wrapper = shallow(<App />);
  const welcome = <h2>Welcome to React</h2>;
  // expect(wrapper.contains(welcome)).to.equal(true);
  expect(wrapper.contains(welcome)).toEqual(true);
});
```

Mohammad Kermani's avatar
Mohammad Kermani committed
1014
All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).<br>
Brian Ng's avatar
Brian Ng committed
1015
Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below.
Dan Abramov's avatar
Dan Abramov committed
1016

1017
1018
1019
1020
1021
1022
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.

```js
expect(wrapper).toContainReact(welcome)
```

1023
To setup jest-enzyme with Create React App, follow the instructions for [initializing your test environment](#initializing-test-environment) to import `jest-enzyme`. **Note that currently only version 2.x is compatible with Create React App.**
1024

1025
```sh
1026
npm install --save-dev jest-enzyme@2.x
1027
1028
```

1029
1030
1031
1032
1033
1034
```js
// src/setupTests.js
import 'jest-enzyme';
```


Dan Abramov's avatar
Dan Abramov committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
### Using Third Party Assertion Libraries

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).

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:

```js
import sinon from 'sinon';
import { expect } from 'chai';
```

and then use them in your tests like you normally do.

1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
### Initializing Test Environment

>Note: this feature is available with `react-scripts@0.4.0` and higher.

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.

For example:

#### `src/setupTests.js`
```js
const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock
```

1066
1067
### Focusing and Excluding Tests

Dan Abramov's avatar
Dan Abramov committed
1068
You can replace `it()` with `xit()` to temporarily exclude a test from being executed.<br>
1069
1070
Similarly, `fit()` lets you focus on a specific test without running any other tests.

Dan Abramov's avatar
Dan Abramov committed
1071
1072
### Coverage Reporting

Dan Abramov's avatar
Dan Abramov committed
1073
Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.<br>
Dan Abramov's avatar
Dan Abramov committed
1074
1075
1076
1077
1078
1079
1080
1081
Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this:

![coverage report](http://i.imgur.com/5bFhnTS.png)

Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow.

### Continuous Integration

1082
1083
1084
1085
1086
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`.

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.

Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
Dan Abramov's avatar
Dan Abramov committed
1087

1088
1089
1090
### On CI servers
#### Travis CI

Brian Ng's avatar
Brian Ng committed
1091
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.
1092
1093
1094
1095
1096
1097
1098
1099
1. Add a `.travis.yml` file to your git repository.
```
language: node_js
node_js:
  - 4
  - 6
cache:
  directories:
1100
1101
    - node_modules
script:
1102
  - npm test
1103
  - npm run build
1104
1105
1106
1107
1108
1109
```
1. Trigger your first build with a git push.
1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.

### On your own environment
##### Windows (cmd.exe)
Dan Abramov's avatar
Dan Abramov committed
1110
1111
1112
1113
1114

```cmd
set CI=true&&npm test
```

1115
1116
1117
1118
```cmd
set CI=true&&npm run build
```

Dan Abramov's avatar
Dan Abramov committed
1119
1120
(Note: the lack of whitespace is intentional.)

1121
##### Linux, macOS (Bash)
Dan Abramov's avatar
Dan Abramov committed
1122
1123
1124
1125
1126

```bash
CI=true npm test
```

1127
1128
1129
1130
1131
1132
1133
```bash
CI=true npm run build
```

The test command will force Jest to run tests once instead of launching the watcher.

>  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.
Dan Abramov's avatar
Dan Abramov committed
1134

1135
The build command will check for linter warnings and fail if any are found.
Dan Abramov's avatar
Dan Abramov committed
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148

### Disabling jsdom

By default, the `package.json` of the generated project looks like this:

```js
  // ...
  "scripts": {
    // ...
    "test": "react-scripts test --env=jsdom"
  }
```

Dan Abramov's avatar
Dan Abramov committed
1149
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.<br>
Dan Abramov's avatar
Dan Abramov committed
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
To help you make up your mind, here is a list of APIs that **need jsdom**:

* Any browser globals like `window` and `document`
* [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render)
* [`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)
* [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html)

In contrast, **jsdom is not needed** for the following APIs:

* [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering)
* [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html)

1162
Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html).
Dan Abramov's avatar
Dan Abramov committed
1163

1164
### Snapshot Testing
Dan Abramov's avatar
Dan Abramov committed
1165

1166
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)
Dan Abramov's avatar
Dan Abramov committed
1167

Orta's avatar
Orta committed
1168
1169
### Editor Integration

1170
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.
Orta's avatar
Orta committed
1171
1172
1173

![VS Code Jest Preview](https://cloud.githubusercontent.com/assets/49038/20795349/a032308a-b7c8-11e6-9b34-7eeac781003f.png)

Dan Abramov's avatar
Dan Abramov committed
1174
## Developing Components in Isolation
1175

Alex Wilmer's avatar
Alex Wilmer committed
1176
Usually, in an app, you have a lot of UI components, and each of them has many different states.
1177
1178
1179
1180
1181
1182
1183
1184
For an example, a simple button component could have following states:

* With a text label.
* With an emoji.
* In the disabled mode.

Usually, it’s hard to see these states without running a sample app or some examples.

1185
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**.
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

![React Storybook Demo](http://i.imgur.com/7CIAWpB.gif)

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.

**Here’s how to setup your app with Storybook:**

First, install the following npm package globally:

```sh
npm install -g getstorybook
```

Then, run the following command inside your app’s directory:

```sh
getstorybook
```

After that, follow the instructions on the screen.

Learn more about React Storybook:

* Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook)
* [GitHub Repo](https://github.com/kadirahq/react-storybook)
1211
* [Documentation](https://storybooks.js.org/docs/react-storybook/basics/introduction/)
1212
1213
* [Snapshot Testing](https://github.com/kadirahq/storyshots) with React Storybook

Dan Abramov's avatar
Dan Abramov committed
1214
1215
1216
1217
## Making a Progressive Web App

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).

1218
1219
## Deployment

1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
`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.<hash>.js` are served with the contents of the `/static/js/main.<hash>.js` file.

### Static Server

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:

```sh
npm install -g serve
serve -s build
```

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.

Run this command to get a full list of the options available:
1234
1235

```sh
1236
serve -h
1237
1238
```

1239
1240
1241
1242
1243
### Other Solutions

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.

Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
1244
1245
1246
1247
1248
1249

```javascript
const express = require('express');
const path = require('path');
const app = express();

1250
app.use(express.static(path.join(__dirname, 'build')));
1251
1252

app.get('/', function (req, res) {
1253
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
1254
1255
1256
1257
1258
});

app.listen(9000);
```

1259
1260
1261
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.

The `build` folder with static assets is the only output produced by Create React App.
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271

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.

### Serving Apps with Client-Side Routing

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.

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:

```diff
1272
 app.use(express.static(path.join(__dirname, 'build')));
1273
1274
1275

-app.get('/', function (req, res) {
+app.get('/*', function (req, res) {
1276
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
1277
1278
1279
 });
```

1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
If you’re using [Apache](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this:

```
    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]
```

It will get copied to the `build` folder when you run `npm run build`.

1291
1292
1293
Now requests to `/todos/42` will be handled correctly both in development and in production.

### Building for Relative Paths
1294

Dan Abramov's avatar
Dan Abramov committed
1295
By default, Create React App produces a build assuming your app is hosted at the server root.<br>
Dan Abramov's avatar
Dan Abramov committed
1296
1297
1298
1299
1300
1301
1302
1303
To override this, specify the `homepage` in your `package.json`, for example:

```js
  "homepage": "http://mywebsite.com/relativepath",
```

This will let Create React App correctly infer the root path to use in the generated HTML file.

1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
#### Serving the Same Build from Different Paths

>Note: this feature is available with `react-scripts@0.9.0` and higher.

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`:

```js
  "homepage": ".",
```

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.
1315

1316
1317
1318
1319
### Azure

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/).

1320
1321
### Firebase

1322
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.
1323

1324
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`.
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380

```sh
    === Project Setup

    First, let's associate this project directory with a Firebase project.
    You can create multiple project aliases by running firebase use --add,
    but for now we'll just set up a default project.

    ? What Firebase project do you want to associate as default? Example app (example-app-fd690)

    === Database Setup

    Firebase Realtime Database Rules allow you to define how your data should be
    structured and when your data can be read from and written to.

    ? What file should be used for Database Rules? database.rules.json
    ✔  Database Rules for example-app-fd690 have been downloaded to database.rules.json.
    Future modifications to database.rules.json will update Database Rules when you run
    firebase deploy.

    === Hosting Setup

    Your public directory is the folder (relative to your project directory) that
    will contain Hosting assets to uploaded with firebase deploy. If you
    have a build process for your assets, use your build's output directory.

    ? What do you want to use as your public directory? build
    ? Configure as a single-page app (rewrite all urls to /index.html)? Yes
    ✔  Wrote build/index.html

    i  Writing configuration info to firebase.json...
    i  Writing project information to .firebaserc...

    ✔  Firebase initialization complete!
```

Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`.

```sh
    === Deploying to 'example-app-fd690'...

    i  deploying database, hosting
    ✔  database: rules ready to deploy.
    i  hosting: preparing build directory for upload...
    Uploading: [==============================          ] 75%✔  hosting: build folder uploaded successfully
    ✔  hosting: 8 files uploaded successfully
    i  starting release process (may take several minutes)...

    ✔  Deploy complete!

    Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
    Hosting URL: https://example-app-fd690.firebaseapp.com
```

For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup).

Dan Abramov's avatar
Dan Abramov committed
1381
### GitHub Pages
1382

1383
1384
>Note: this feature is available with `react-scripts@0.2.0` and higher.

Dan Abramov's avatar
Dan Abramov committed
1385
1386
#### Step 1: Add `homepage` to `package.json`

Alex Wilmer's avatar
Alex Wilmer committed
1387
1388
**The step below is important!**<br>
**If you skip it, your app will not deploy correctly.**
Dan Abramov's avatar
Dan Abramov committed
1389

Dan Abramov's avatar
Dan Abramov committed
1390
Open your `package.json` and add a `homepage` field:
1391
1392

```js
1393
  "homepage": "https://myusername.github.io/my-app",
1394
1395
```

1396
1397
Create React App uses the `homepage` field to determine the root URL in the built HTML file.

Dan Abramov's avatar
Dan Abramov committed
1398
#### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`
Dan Abramov's avatar
Dan Abramov committed
1399

1400
Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
1401

1402
To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run:
1403
1404

```sh
1405
1406
1407
npm install --save-dev gh-pages
```

1408
Add the following scripts in your `package.json`:
1409
1410
1411
1412
1413

```js
  // ...
  "scripts": {
    // ...
1414
1415
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
1416
  }
1417
1418
```

1419
The `predeploy` script will run automatically before `deploy` is run.
1420

Dan Abramov's avatar
Dan Abramov committed
1421
1422
#### Step 3: Deploy the site by running `npm run deploy`

1423
1424
1425
1426
1427
Then run:

```sh
npm run deploy
```
1428

1429
#### Step 4: Ensure your project’s settings use `gh-pages`
Dan Abramov's avatar
Dan Abramov committed
1430
1431
1432
1433
1434
1435

Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch:

<img src="http://i.imgur.com/HUjEr9l.png" width="500" alt="gh-pages branch setting">

#### Step 5: Optionally, configure the domain
Dan Abramov's avatar
Dan Abramov committed
1436

1437
1438
You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder.

Dan Abramov's avatar
Dan Abramov committed
1439
1440
#### Notes on client-side routing

1441
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:
Dan Abramov's avatar
Dan Abramov committed
1442

1443
1444
1445
* 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.
* 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).

1446
1447
### Heroku

Dan Abramov's avatar
Dan Abramov committed
1448
Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).<br>
1449
You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration).
1450

1451
#### Resolving Heroku Deployment Errors
1452

1453
1454
1455
1456
1457
Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases.

##### "Module not found: Error: Cannot resolve 'file' or 'directory'"

If you get something like this:
1458

1459
```
1460
remote: Failed to create a production build. Reason:
1461
remote: Module not found: Error: Cannot resolve 'file' or 'directory'
1462
MyDirectory in /tmp/build_1234/src
1463
1464
```

1465
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.
1466
1467

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.
1468

1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
##### "Could not find a required file."

If you exclude or ignore necessary files from the package you will see a error similar this one:

```
remote: Could not find a required file.
remote:   Name: `index.html`
remote:   Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public
remote:
remote: npm ERR! Linux 3.13.0-105-generic
remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build"
```

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`.

1484
1485
1486
1487
### Modulus

See the [Modulus blog post](http://blog.modulus.io/deploying-react-apps-on-modulus) on how to deploy your react app to Modulus.

1488
### Netlify
1489

1490
**To do a manual deploy to Netlify’s CDN:**
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506

```sh
npm install netlify-cli
netlify deploy
```

Choose `build` as the path to deploy.

**To setup continuous delivery:**

With this setup Netlify will build and deploy when you push to git or open a pull request:

1. [Start a new netlify project](https://app.netlify.com/signup)
2. Pick your Git hosting service and select your repository
3. Click `Build your site`

Ville Immonen's avatar
Ville Immonen committed
1507
**Support for client-side routing:**
1508
1509
1510
1511
1512
1513
1514
1515
1516

To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules:

```
/*  /index.html  200
```

When you build the project, Create React App will place the `public` folder contents into the build output.

1517
1518
### Now

1519
1520
1521
1522
1523
1524
1525
[now](https://zeit.co/now) offers a zero-configuration single-command deployment.

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`.

2. Install `serve` by running `npm install --save serve`.

3. Add this line to `scripts` in `package.json`:
1526

1527
    ```
1528
    "now-start": "serve -s build/",
1529
    ```
1530

1531
4. Run `now` from your project directory. You will see a **now.sh** URL in your output like this:
1532

1533
1534
1535
    ```
    > Ready! https://your-project-dirname-tpspyhtdtk.now.sh (copied to clipboard)
    ```
1536

1537
1538
1539
    Paste that URL into your browser when the build is complete, and you will see your deployed app.

Details are available in [this article.](https://zeit.co/blog/now-static)
1540

1541
1542
1543
1544
### S3 and CloudFront

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/).

1545
1546
### Surge

Dan Abramov's avatar
Dan Abramov committed
1547
1548
1549
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.

When asked about the project path, make sure to specify the `build` folder, for example:
1550
1551
1552
1553
1554

```sh
       project path: /path/to/project/build
```

Brian Ng's avatar
Brian Ng committed
1555
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).
1556

1557
1558
1559
1560
1561
1562
## Advanced Configuration

You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).

Variable | Development | Production | Usage
:--- | :---: | :---: | :---
1563
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. <!-- TODO: enable with 0.10: 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. -->
1564
1565
1566
1567
1568
1569
HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host.
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.
HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode.
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.
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.

1570
1571
## Troubleshooting

1572
1573
1574
1575
1576
1577
1578
1579
1580
### `npm start` doesn’t detect changes

When you save a file while `npm start` is running, the browser should refresh with the updated code.<br>
If this doesn’t happen, try one of the following workarounds:

* If your project is in a Dropbox folder, try moving it out.
* 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.
* 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).
* 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).
1581
* 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.
1582
* 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.
1583
1584
1585

If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659).

1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
### `npm test` hangs on macOS Sierra

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).

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:

* [facebook/jest#1767](https://github.com/facebook/jest/issues/1767)
* [facebook/watchman#358](https://github.com/facebook/watchman/issues/358)
* [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259)

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:

```
watchman shutdown-server
brew update
brew reinstall watchman
```

You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page.

1606
If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
1607
1608
1609

There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.

1610
1611
1612
1613
### `npm run build` silently fails

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.

1614
1615
1616
### `npm run build` fails on Heroku

This may be a problem with case sensitive filenames.
1617
Please refer to [this section](#resolving-heroku-deployment-errors).
1618

Dan Abramov's avatar
Dan Abramov committed
1619
## Something Missing?
Dan Abramov's avatar
Dan Abramov committed
1620

Ville Immonen's avatar
Ville Immonen committed
1621
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)
For faster browsing, not all history is shown. View entire blame