README.md 126 KB
Newer Older
Joe Haddad's avatar
Joe Haddad committed
2001
instructions for using other methods. *Be sure to always use an
2002
2003
incognito window to avoid complications with your browser cache.*

Dan Abramov's avatar
Dan Abramov committed
2004
1. If possible, configure your production environment to serve the generated
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
`service-worker.js` [with HTTP caching disabled](http://stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours).
If that's not possible—[GitHub Pages](#github-pages), for instance, does not
allow you to change the default 10 minute HTTP cache lifetime—then be aware
that if you visit your production site, and then revisit again before
`service-worker.js` has expired from your HTTP cache, you'll continue to get
the previously cached assets from the service worker. If you have an immediate
need to view your updated production deployment, performing a shift-refresh
will temporarily disable the service worker and retrieve all assets from the
network.

1. Users aren't always familiar with offline-first web apps. It can be useful to
[let the user know](https://developers.google.com/web/fundamentals/instant-and-offline/offline-ux#inform_the_user_when_the_app_is_ready_for_offline_consumption)
when the service worker has finished populating your caches (showing a "This web
app works offline!" message) and also let them know when the service worker has
fetched the latest updates that will be available the next time they load the
page (showing a "New content is available; please refresh." message). Showing
this messages is currently left as an exercise to the developer, but as a
Dan Abramov's avatar
Dan Abramov committed
2022
starting point, you can make use of the logic included in [`src/registerServiceWorker.js`](src/registerServiceWorker.js), which
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
demonstrates which service worker lifecycle events to listen for to detect each
scenario, and which as a default, just logs appropriate messages to the
JavaScript console.

1. By default, the generated service worker file will not intercept or cache any
cross-origin traffic, like HTTP [API requests](#integrating-with-an-api-backend),
images, or embeds loaded from a different domain. If you would like to use a
runtime caching strategy for those requests, you can [`eject`](#npm-run-eject)
and then configure the
[`runtimeCaching`](https://github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject)
option in the `SWPrecacheWebpackPlugin` section of
[`webpack.config.prod.js`](../config/webpack.config.prod.js).

### Progressive Web App Metadata

The default configuration includes a web app manifest located at
[`public/manifest.json`](public/manifest.json), that you can customize with
details specific to your web application.

When a user adds a web app to their homescreen using Chrome or Firefox on
Android, the metadata in [`manifest.json`](public/manifest.json) determines what
icons, names, and branding colors to use when the web app is displayed.
[The Web App Manifest guide](https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/)
provides more context about what each field means, and how your customizations
will affect your users' experience.

2049
2050
## Analyzing the Bundle Size

2051
2052
2053
2054
2055
2056
2057
2058
When your app grows in size, it's easy for bundles to become bloated. The first step to solving large bundles is understanding what's in them!

There are many different tools available to analyze bundles, but they typically rely on either **sourcemaps** or **webpack-specific JSON stats**.

### Using Sourcemaps

When building for production, sourcemaps are automatically created adjacent to the JS files in `build/static/js`.

2059
2060
2061
2062
2063
2064
[Source map explorer](https://www.npmjs.com/package/source-map-explorer) analyzes
JavaScript bundles using the source maps. This helps you understand where code
bloat is coming from.

To add Source map explorer to a Create React App project, follow these steps:

2065
2066
```sh
npm install --save source-map-explorer
2067
```
2068
2069
2070
2071
2072

Alternatively you may use `yarn`:

```sh
yarn add source-map-explorer
2073
2074
```

2075
Then in `package.json`, add the following line to `scripts`:
2076
2077
2078

```diff
   "scripts": {
2079
+    "analyze": "source-map-explorer build/static/js/main.*",
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
     "start": "react-scripts start",
     "build": "react-scripts build",
     "test": "react-scripts test --env=jsdom",
```

Then to analyze the bundle run the production build then run the analyze
script.

```
npm run build
npm run analyze
```

2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
### Using Webpack Stats JSON

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

Webpack can produce a JSON manifest that details the bundles, and several tools can use that file to do analysis.

Unlike with sourcemaps, the JSON file isn't created automatically on build. You must pass a `--stats` flag:

```sh
npm run build -- --stats
```

Once the build is complete, you should have a JSON file located at `build/bundle-stats.json`.

The quickest way to get insight into your bundle is to drag and drop that JSON file into [Webpack Visualizer](https://chrisbateman.github.io/webpack-visualizer/).

2109
Another very popular tool is [`webpack-bundle-analyzer`](https://github.com/webpack-contrib/webpack-bundle-analyzer).
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131

To use `webpack-bundle-analyzer`, start by installing it from NPM:

```sh
npm install --save webpack-bundle-analyzer
# or, with Yarn:
yarn add webpack-bundle-analyzer
```


In `package.json`, add the following line to `scripts`:

```diff
   "scripts": {
+    "analyze": "npm run build -- --stats && webpack-bundle-analyzer build/bundle-stats.json",
     "start": "react-scripts start",
     "build": "react-scripts build",
     "test": "react-scripts test --env=jsdom",
```

When you run `npm run analyze`, a new build will be created, and a browser tab should open automatically, displaying the sizes of the modules within your bundle.

2132
2133
## Deployment

JANG SUN HYUK's avatar
JANG SUN HYUK committed
2134
`npm run build` creates a `build` directory with a production build of your app. Set up your favorite 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.
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147

### 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:
2148
2149

```sh
2150
serve -h
2151
2152
```

2153
2154
2155
2156
2157
### 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/):
2158
2159
2160
2161
2162
2163

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

2164
app.use(express.static(path.join(__dirname, 'build')));
2165
2166

app.get('/', function (req, res) {
2167
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
2168
2169
2170
2171
2172
});

app.listen(9000);
```

2173
2174
2175
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.
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185

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
2186
 app.use(express.static(path.join(__dirname, 'build')));
2187
2188
2189

-app.get('/', function (req, res) {
+app.get('/*', function (req, res) {
2190
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
2191
2192
2193
 });
```

2194
If you’re using [Apache HTTP Server](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this:
2195
2196
2197
2198
2199
2200
2201
2202

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

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

If you’re using [Apache Tomcat](http://tomcat.apache.org/), you need to follow [this Stack Overflow answer](https://stackoverflow.com/a/41249464/4878474).
2206

2207
2208
Now requests to `/todos/42` will be handled correctly both in development and in production.

2209
When users install your app to the homescreen of their device the default configuration will make a shortcut to `/`. This may not work if you don't use a client-side router and expect the app to be served from `/index.html`. In this case, the web app manifest at [`public/manifest.json`](public/manifest.json) and change `start_url` to `./index.html`.
2210

2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
### Service Worker Considerations

[Navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)
for URLs like `/todos/42` will not be intercepted by the
[service worker](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers)
created by the production build. Navigations for those URLs will always
require a network connection, as opposed to navigations for `/` and
`/index.html`, both of which will be served from the cache by the service worker
and work without requiring a network connection.

If you are using the `pushState` history API and would like to enable service
worker support for navigations to URLs like `/todos/42`, you need to
2223
[`npm eject`](#npm-run-eject) and enable the [`navigateFallback`](https://github.com/GoogleChrome/sw-precache#navigatefallback-string)
2224
2225
2226
and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp)
options of the `SWPreachePlugin` [configuration](../config/webpack.config.prod.js).

2227
>Note: This is a [change in default behavior](https://github.com/facebook/create-react-app/issues/3248),
2228
2229
2230
as earlier versions of `create-react-app` shipping with `navigateFallback`
enabled by default.

2231
### Building for Relative Paths
2232

Dan Abramov's avatar
Dan Abramov committed
2233
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
2234
2235
2236
2237
2238
2239
2240
2241
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.

2242
2243
2244
2245
2246
2247
2248
2249
2250
**Note**: If you are using `react-router@^4`, you can root `<Link>`s using the `basename` prop on any `<Router>`.<br>
More information [here](https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string).<br>
<br>
For example:
```js
<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="/calendar/today">
```

2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
#### 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.
2262

2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
### Customizing Environment Variables for Arbitrary Build Environments

You can create an arbitrary build environment by creating a custom `.env` file and loading it using [env-cmd](https://www.npmjs.com/package/env-cmd).

For example, to create a build environment for a staging environment:

1. Create a file called `.env.staging`
1. Set environment variables as you would any other `.env` file (e.g. `REACT_APP_API_URL=http://api-staging.example.com`)
1. Install [env-cmd](https://www.npmjs.com/package/env-cmd)
    ```sh
    $ npm install env-cmd --save
    $ # or
    $ yarn add env-cmd
    ```
1. Add a new script to your `package.json`, building with your new environment:
    ```json
    {
      "scripts": {
        "build:staging": "env-cmd .env.staging npm run build",
      }
    }
    ```

Now you can run `npm run build:staging` to build with the staging environment config.
You can specify other environments in the same way.

Variables in `.env.production` will be used as fallback because `NODE_ENV` will always be set to `production` for a build.

2291
### [Azure](https://azure.microsoft.com/)
2292

2293
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.
2294

2295
2296
See [this](https://medium.com/@strid/host-create-react-app-on-azure-986bc40d5bf2#.pycfnafbg) blog post or [this](https://github.com/ulrikaugustsson/azure-appservice-static) repo for a way to use automatic deployment to Azure App Service.

2297
### [Firebase](https://firebase.google.com/)
2298

2299
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.
2300

2301
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`.
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337

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

2338
IMPORTANT: you need to set proper HTTP caching headers for `service-worker.js` file in `firebase.json` file or you will not be able to see changes after first deployment ([issue #2440](https://github.com/facebook/create-react-app/issues/2440)). It should be added inside `"hosting"` key like next:
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349

```
{
  "hosting": {
    ...
    "headers": [
      {"source": "/service-worker.js", "headers": [{"key": "Cache-Control", "value": "no-cache"}]}
    ]
    ...
```

2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
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).

2370
### [GitHub Pages](https://pages.github.com/)
2371

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

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

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

2379
Open your `package.json` and add a `homepage` field for your project:
2380

2381
```json
2382
  "homepage": "https://myusername.github.io/my-app",
2383
2384
```

2385
2386
2387
2388
2389
2390
or for a GitHub user page:

```json
  "homepage": "https://myusername.github.io",
```

2391
2392
2393
2394
2395
or for a custom domain page:
```json
  "homepage": "https://mywebsite.com",
```

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

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

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

2402
To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run:
2403
2404

```sh
2405
2406
2407
2408
2409
2410
2411
npm install --save gh-pages
```

Alternatively you may use `yarn`:

```sh
yarn add gh-pages
2412
2413
```

2414
Add the following scripts in your `package.json`:
2415

2416
```diff
2417
  "scripts": {
2418
2419
2420
2421
+   "predeploy": "npm run build",
+   "deploy": "gh-pages -d build",
    "start": "react-scripts start",
    "build": "react-scripts build",
2422
2423
```

2424
The `predeploy` script will run automatically before `deploy` is run.
2425

2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
If you are deploying to a GitHub user page instead of a project page you'll need to make two
additional modifications:

1. First, change your repository's source branch to be any branch other than **master**.
1. Additionally, tweak your `package.json` scripts to push deployments to **master**:
```diff
  "scripts": {
    "predeploy": "npm run build",
-   "deploy": "gh-pages -d build",
+   "deploy": "gh-pages -b master -d build",
```

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

2440
2441
2442
2443
2444
Then run:

```sh
npm run deploy
```
2445

2446
#### Step 4: Ensure your project’s settings use `gh-pages`
Dan Abramov's avatar
Dan Abramov committed
2447
2448
2449
2450
2451
2452

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
2453

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

2456
2457
2458
2459
2460
2461
Your CNAME file should look like this:

```
mywebsite.com
```

Dan Abramov's avatar
Dan Abramov committed
2462
2463
#### Notes on client-side routing

2464
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
2465

2466
* You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to `hashHistory` for this effect, but the URL will be longer and more verbose (for example, `http://user.github.io/todomvc/#/todos/42?_k=yknaj`). [Read more](https://reacttraining.com/react-router/web/api/Router) about different history implementations in React Router.
2467
2468
* 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).

2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
#### Troubleshooting

##### "/dev/tty: No such a device or address"

If, when deploying, you get `/dev/tty: No such a device or address` or a similar error, try the follwing:

1. Create a new [Personal Access Token](https://github.com/settings/tokens)
2. `git remote set-url origin https://<user>:<token>@github.com/<user>/<repo>` .
3. Try `npm run deploy again`

2479
### [Heroku](https://www.heroku.com/)
2480

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

2484
#### Resolving Heroku Deployment Errors
2485

2486
2487
2488
2489
2490
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:
2491

2492
```
2493
remote: Failed to create a production build. Reason:
2494
remote: Module not found: Error: Cannot resolve 'file' or 'directory'
2495
MyDirectory in /tmp/build_1234/src
2496
2497
```

2498
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.
2499
2500

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

2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
##### "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`.

2517
### [Netlify](https://www.netlify.com/)
2518

2519
**To do a manual deploy to Netlify’s CDN:**
2520
2521

```sh
Elie's avatar
Elie committed
2522
npm install netlify-cli -g
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
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
2536
**Support for client-side routing:**
2537
2538
2539
2540
2541
2542
2543
2544
2545

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.

2546
### [Now](https://zeit.co/now)
2547

2548
Now offers a zero-configuration single-command deployment. You can use `now` to deploy your app for free.
2549
2550
2551

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

2552
2. Build your app by running `npm run build`.
2553

2554
3. Move into the build directory by running `cd build`.
2555

2556
4. Run `now --name your-project-name` from within the build directory. You will see a **now.sh** URL in your output like this:
2557

2558
    ```
2559
    > Ready! https://your-project-name-tpspyhtdtk.now.sh (copied to clipboard)
2560
    ```
2561

2562
2563
    Paste that URL into your browser when the build is complete, and you will see your deployed app.

2564
Details are available in [this article.](https://zeit.co/blog/unlimited-static)
2565

2566
### [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/)
2567

2568
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 and CloudFront.
2569

2570
### [Surge](https://surge.sh/)
2571

Dan Abramov's avatar
Dan Abramov committed
2572
2573
2574
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:
2575
2576
2577
2578
2579

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

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

2582
2583
2584
2585
2586
2587
## 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
:--- | :---: | :---: | :---
Joe Haddad's avatar
Joe Haddad committed
2588
BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to `npm start` will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the `.js` extension.
2589
2590
2591
2592
2593
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.
2594
REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebook/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable points to your editor’s bin folder. You can also set it to `none` to disable it completely.
Joe Haddad's avatar
Joe Haddad committed
2595
CHOKIDAR_USEPOLLING | :white_check_mark: | :x: | When set to `true`, the watcher runs in polling mode, as necessary inside a VM. Use this option if `npm start` isn't detecting changes.
Joe Haddad's avatar
Joe Haddad committed
2596
GENERATE_SOURCEMAP | :x: | :white_check_mark: | When set to `false`, source maps are not generated for a production build. This solves OOM issues on some smaller machines.
Dan Abramov's avatar
Dan Abramov committed
2597
NODE_PATH | :white_check_mark: |  :white_check_mark: | Same as [`NODE_PATH` in Node.js](https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders), but only relative folders are allowed. Can be handy for emulating a monorepo setup by setting `NODE_PATH=src`.
2598

2599
2600
## Troubleshooting

2601
2602
2603
2604
2605
2606
### `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.
2607
* 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/facebook/create-react-app/issues/1164) due to a Webpack bug.
Joe Haddad's avatar
Joe Haddad committed
2608
* Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in [“Adjusting Your Text Editor”](https://webpack.js.org/guides/development/#adjusting-your-text-editor).
2609
* 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).
Dan Abramov's avatar
Dan Abramov committed
2610
* On Linux and macOS, you might need to [tweak system settings](https://github.com/webpack/docs/wiki/troubleshooting#not-enough-watchers) to allow more watchers.
2611
* 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.
2612

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

2615
### `npm test` hangs or crashes on macOS Sierra
2616

2617
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 [facebook/create-react-app#713](https://github.com/facebook/create-react-app/issues/713).
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634

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.

2635
If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
2636
2637
2638

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

2639
### `npm run build` exits too early
2640

2641
It is reported that `npm run build` can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:
2642
2643
2644
2645

>  The build failed because the process exited too early. This probably means the system ran out of memory or someone called `kill -9` on the process.

If you are completely sure that you didn't terminate the process, consider [adding some swap space](https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04) to the machine you’re building on, or build the project locally.
2646

2647
2648
2649
### `npm run build` fails on Heroku

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

2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
### Moment.js locales are missing

If you use a [Moment.js](https://momentjs.com/), you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of [all the locales provided by Moment.js](https://momentjs.com/#multiple-locale-support).

To add a specific Moment.js locale to your bundle, you need to import it explicitly.<br>
For example:

```js
import moment from 'moment';
import 'moment/locale/fr';
```

If import multiple locales this way, you can later switch between them by calling `moment.locale()` with the locale name:

```js
import moment from 'moment';
import 'moment/locale/fr';
import 'moment/locale/es';

// ...

moment.locale('fr');
```

This will only work for locales that have been explicitly imported before.

2678
2679
### `npm run build` fails to minify

2680
2681
Some third-party packages don't compile their code to ES5 before publishing to npm. This often causes problems in the ecosystem because neither browsers (except for most modern versions) nor some tools currently support all ES6 features. We recommend to publish code on npm as ES5 at least for a few more years.

2682
2683
<br>
To resolve this:
2684
2685
2686
2687

1. Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled.
  * Note: Create React App can consume both CommonJS and ES modules. For Node.js compatibility, it is recommended that the main entry point is CommonJS. However, they can optionally provide an ES module entry point with the `module` field in `package.json`. Note that **even if a library provides an ES Modules version, it should still precompile other ES6 features to ES5 if it intends to support older browsers**.

2688
2. Fork the package and publish a corrected version yourself.
2689

2690
2691
3. If the dependency is small enough, copy it to your `src/` folder and treat it as application code.

2692
2693
In the future, we might start automatically compiling incompatible third-party modules, but it is not currently supported. This approach would also slow down the production builds.

2694
2695
## Alternatives to Ejecting

2696
[Ejecting](#npm-run-eject) lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to *fork* `react-scripts` and any other packages you need. [This article](https://auth0.com/blog/how-to-configure-create-react-app/) dives into how to do it in depth. You can find more discussion in [this issue](https://github.com/facebook/create-react-app/issues/682).
2697

Dan Abramov's avatar
Dan Abramov committed
2698
## Something Missing?
Dan Abramov's avatar
Dan Abramov committed
2699

2700
If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebook/create-react-app/issues) or [contribute some!](https://github.com/facebook/create-react-app/edit/master/packages/react-scripts/template/README.md)
For faster browsing, not all history is shown. View entire blame