1
Fork 0

Update readme

This commit is contained in:
viktorstrate 2020-02-10 12:22:42 +01:00
parent 2bbb1740ba
commit 5a0f03268d
2 changed files with 321 additions and 380 deletions

View File

@ -1,12 +1,15 @@
# PhotoView
![screenshot](/screenshots/main-window.png)
**SERVER REWRITE. The api is currently being rewritten in Golang, use branch `old-nodejs-server` for the most stable release**
![screenshot](./screenshots/main-window.png)
## Demo site
Visit https://photos.qpqp.dk/
Username: __demo__
Password: __demo__
Username: **demo**
Password: **demo**
## Aim of the project
@ -14,7 +17,8 @@ The aim of this project is to make a simple and user-friendly photo gallery appl
that is easy to host on a personal server, to easily view the photos located on that server.
## Main features
> The software is still in early development, and many of the following features, have not been implemented yet.
> The software is still in early development, and many of the following features, may not have been fully implemented yet.
- **Closely tied to the file system**. The website presents the images found on the local filesystem of the server, directories are mapped to albums.
- **User management**. Each user is created along with a path on the local filesystem, photos within that path can be accessed by that user.
@ -47,7 +51,7 @@ If the endpoint or the port hasn't been changed in the `docker-compose.yml` file
If everything is setup correctly, you should be presented with an initial setup wizard, when accessing the website the first time.
![Initial setup](/screenshots/initial-setup.png)
![Initial setup](./screenshots/initial-setup.png)
Enter a new username and password.
@ -61,40 +65,23 @@ The photos will have to be scanned for the photos to show up, you can force a sc
## Setup development environment
> This projected is based of the [GrandStack](https://grandstack.io/) starter project.
### Local setup
1. [Download Neo4j Desktop](https://neo4j.com/download/)
2. Install and open Neo4j Desktop.
3. Create a new DB by clicking "New Graph", and clicking "create local graph".
4. Set password to "letmein" (as suggested by `api/.env`), and click "Create".
5. Make sure that the default credentials in `api/.env` are used. Leave them as follows: `NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=letmein`
6. Click "Manage".
7. Click "Plugins".
8. Find "APOC" and click "Install".
9. Click the "play" button at the top of left the screen, which should start the server. _(screenshot 2)_
10. Wait until it says "RUNNING".
11. Proceed forward with the rest of the tutorial.
1. Install a local mysql server, and make a new database
2. Rename `/api/example.env` to `.env` and update the `MYSQL_URL` field
3. Rename `/ui/example.env` to `.env`
### [`/api`](./api)
#### Install dependencies
```bash
(cd ./ui && npm install)
(cd ./api && npm install)
```
#### Start API server
```bash
cd ./api && npm start
cd ./api && go run server/server.go
```
### [`/ui`](./ui)
This will start the GraphQL API in the foreground, so in another terminal session start the UI development server:
The above command will start the GraphQL API in the foreground, so in another terminal session start the UI development server:
#### Start UI server
@ -103,4 +90,4 @@ cd ./ui && npm start
```
The site can now be accessed at [localhost:1234](http://localhost:1234).
And the graphql playground at [localhost:4001/graphql](http://localhost:4001/graphql)
And the graphql playground at [localhost:4001](http://localhost:4001)

View File

@ -1,76 +1,5 @@
# GRANDstack Starter - UI
This directory contains a React app (bootstrapped with Create React App) that uses Apollo Client to query a GraphQL API.
The template app queries for a list of users from the GraphQL API and displays them in a list.
## Quickstart
Install dependencies:
```
npm install
```
Start the development server:
```
npm start
```
This will serve the app on `http://localhost:3000`
![](img/default-app.png)
## Configure
Configuration is done with environment variables specified in `.env`
Edit `.env` to specify the URI of the GraphQL API. The default is `http://localhost:4000`
*.env*
```
REACT_APP_GRAPHQL_URI=http://localhost:4000
```
## Build and Deploy (with Zeit Now)
Be sure you've [deployed the GraphQL Service](../api#deployment) and have the URI of the GraphQL service you've deployed.
### Configure
Create `.env.production` to override `.env` used for local development. For example if you've already deployed the GraphQL service, specify the GraphQL service URI in `.env.production`.
To take advantage of Zeit Now's free hosting tier you'll need to disable source maps (becuase the source map file size exceeds the maximum 1M for Now's free tier). Add `GENERATE_SOURCEMAP=false` to `.env.production`.
So your `.env.production` should look like this (replacing your own GraphQL API URI):
*.env.production*
```
REACT_APP_GRAPHQL_URI=https://grand-stack-starter-api-pqdeodpvok.now.sh
GENERATE_SOURCEMAP=false
```
### Deploy With Zeit Now
To use [Zeit Now](https://zeit.co/now) you'll need to download Zeit Desktop if you haven't already. And then run:
```
now
```
this will deploy your React app to Zeit Now and give you a unqiue URL for your app. For example: https://grand-stack-starter-ui-pwntmhvvwr.now.sh
## Material-UI
[Material-UI](https://material-ui.com/) components are included. See [the docs](https://material-ui.com/getting-started/usage/) for an overview of the components included. This starter example makes use of the Material-UI data Table (and related) components.
## Create React App
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
Below you will find some information on how to perform common tasks.<br>
@ -180,8 +109,8 @@ You can find the most recent version of this guide [here](https://github.com/fac
Create React App is divided into two packages:
* `create-react-app` is a global command-line utility that you use to create new projects.
* `react-scripts` is a development dependency in the generated projects (including this one).
- `create-react-app` is a global command-line utility that you use to create new projects.
- `react-scripts` is a development dependency in the generated projects (including this one).
You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
@ -220,8 +149,8 @@ my-app/
For the project to build, **these files must exist with exact filenames**:
* `public/index.html` is the page template;
* `src/index.js` is the JavaScript entry point.
- `public/index.html` is the page template;
- `src/index.js` is the JavaScript entry point.
You can delete or rename the other files.
@ -282,12 +211,12 @@ You can refer [to the React documentation](https://reactjs.org/docs/react-dom.ht
This project supports a superset of the latest JavaScript standard.<br>
In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
* [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
* [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
* [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
* [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
* [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
* [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
- [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
- [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
- [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
- [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
- [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
- [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
@ -295,9 +224,9 @@ While we recommend using experimental proposals with some caution, Facebook heav
Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
* [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
* [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
- [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
- [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
- [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.
@ -345,7 +274,8 @@ Then add the block below to your `launch.json` file and put it inside the `.vsco
```json
{
"version": "0.2.0",
"configurations": [{
"configurations": [
{
"name": "Chrome",
"type": "chrome",
"request": "launch",
@ -354,9 +284,11 @@ Then add the block below to your `launch.json` file and put it inside the `.vsco
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
}]
}
]
}
```
> Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
@ -391,9 +323,9 @@ Alternatively you may use `yarn`:
yarn add husky lint-staged prettier
```
* `husky` makes it easy to use githooks as if they are npm scripts.
* `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
* `prettier` is the JavaScript formatter we will run before commits.
- `husky` makes it easy to use githooks as if they are npm scripts.
- `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
- `prettier` is the JavaScript formatter we will run before commits.
Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
@ -461,7 +393,7 @@ For example:
### `Button.js`
```js
import React, { Component } from 'react';
import React, { Component } from 'react'
class Button extends Component {
render() {
@ -469,23 +401,22 @@ class Button extends Component {
}
}
export default Button; // Dont forget to use export default!
export default Button // Dont forget to use export default!
```
### `DangerButton.js`
```js
import React, { Component } from 'react';
import Button from './Button'; // Import a component from another file
import React, { Component } from 'react'
import Button from './Button' // Import a component from another file
class DangerButton extends Component {
render() {
return <Button color="red" />;
return <Button color="red" />
}
}
export default DangerButton;
export default DangerButton
```
Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
@ -496,9 +427,9 @@ Named exports are useful for utility modules that export several functions. A mo
Learn more about ES6 modules:
* [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
* [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
* [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
- [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
- [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
- [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
## Code Splitting
@ -511,14 +442,15 @@ Here is an example:
### `moduleA.js`
```js
const moduleA = 'Hello';
const moduleA = 'Hello'
export { moduleA };
export { moduleA }
```
### `App.js`
```js
import React, { Component } from 'react';
import React, { Component } from 'react'
class App extends Component {
handleClick = () => {
@ -528,19 +460,19 @@ class App extends Component {
})
.catch(err => {
// Handle failure
});
};
})
}
render() {
return (
<div>
<button onClick={this.handleClick}>Load</button>
</div>
);
)
}
}
export default App;
export default App
```
This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
@ -568,13 +500,13 @@ This project setup uses [Webpack](https://webpack.js.org/) for handling all asse
### `Button.js`
```js
import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles
import React, { Component } from 'react'
import './Button.css' // Tell Webpack that Button.js uses these styles
class Button extends Component {
render() {
// You can use them as regular CSS styles
return <div className="Button" />;
return <div className="Button" />
}
}
```
@ -704,7 +636,7 @@ Now running `npm start` and `npm run build` also builds Sass files.
`node-sass` has been reported as having the following issues:
- `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker.
- `node-sass --watch` has been reported to have _performance issues_ in certain conditions when used in a virtual machine or with docker.
- Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939)
@ -723,17 +655,17 @@ To reduce the number of requests to the server, importing images that are less t
Here is an example:
```js
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
import React from 'react'
import logo from './logo.png' // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
console.log(logo) // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
return <img src={logo} alt="Logo" />
}
export default Header;
export default Header
```
This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths.
@ -770,9 +702,9 @@ Note that we normally encourage you to `import` assets in JavaScript files inste
For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files).
This mechanism provides a number of benefits:
* Scripts and stylesheets get minified and bundled together to avoid extra network requests.
* Missing files cause compilation errors instead of 404 errors for your users.
* Result filenames include content hashes so you dont need to worry about browsers caching their old versions.
- Scripts and stylesheets get minified and bundled together to avoid extra network requests.
- Missing files cause compilation errors instead of 404 errors for your users.
- Result filenames include content hashes so you dont need to worry about browsers caching their old versions.
However there is an **escape hatch** that you can use to add an asset outside of the module system.
@ -781,7 +713,7 @@ If you put a file into the `public` folder, it will **not** be processed by Webp
Inside `index.html`, you can use it like this:
```html
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
```
Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, youll have to copy it there to explicitly specify your intention to make this file a part of the build.
@ -801,19 +733,19 @@ render() {
Keep in mind the downsides of this approach:
* None of the files in `public` folder get post-processed or minified.
* Missing files will not be called at compilation time, and will cause 404 errors for your users.
* Result filenames wont include content hashes so youll need to add query arguments or rename them every time they change.
- None of the files in `public` folder get post-processed or minified.
- Missing files will not be called at compilation time, and will cause 404 errors for your users.
- Result filenames wont include content hashes so youll need to add query arguments or rename them every time they change.
### When to Use the `public` Folder
Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript.
The `public` folder is useful as a workaround for a number of less common cases:
* You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest).
* You have thousands of images and need to dynamically reference their paths.
* You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code.
* Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag.
- You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest).
- You have thousands of images and need to dynamically reference their paths.
- You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code.
- Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag.
Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them.
@ -824,7 +756,7 @@ When you include a script in the HTML file that defines global variables and try
You can avoid this by reading the global variable explicitly from the `window` object, for example:
```js
const $ = window.$;
const $ = window.$
```
This makes it obvious you are using a global variable intentionally rather than because of a typo.
@ -847,19 +779,19 @@ Alternatively you may use `yarn`:
yarn add react-bootstrap bootstrap@3
```
Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file:
Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your `src/index.js` file:
```js
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/css/bootstrap-theme.css'
// Put any other imports below so that CSS from your
// components takes precedence over default styles.
```
Import required React Bootstrap components within ```src/App.js``` file or your custom component files:
Import required React Bootstrap components within `src/App.js` file or your custom component files:
```js
import { Navbar, Jumbotron, Button } from 'react-bootstrap';
import { Navbar, Jumbotron, Button } from 'react-bootstrap'
```
Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap.
@ -869,9 +801,9 @@ Now you are ready to use the imported React Bootstrap components within your com
Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br>
We suggest the following approach:
* Create a new package that depends on the package you wish to customize, e.g. Bootstrap.
* Add the necessary build steps to tweak the theme, and publish your package on npm.
* Install your own theme npm package as a dependency of your app.
- Create a new package that depends on the package you wish to customize, e.g. Bootstrap.
- Add the necessary build steps to tweak the theme, and publish your package on npm.
- Install your own theme npm package as a dependency of your app.
Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps.
@ -971,7 +903,7 @@ Having access to the `NODE_ENV` is also useful for performing actions conditiona
```js
if (process.env.NODE_ENV !== 'production') {
analytics.disable();
analytics.disable()
}
```
@ -989,8 +921,8 @@ You can also access the environment variables starting with `REACT_APP_` in the
Note that the caveats from the above section apply:
* Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work.
* The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server).
- Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work.
- The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server).
### Adding Temporary Environment Variables In Your Shell
@ -1026,6 +958,7 @@ To define permanent environment variables, create a file called `.env` in the ro
```
REACT_APP_SECRET_CODE=abcdef
```
> Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid [accidentally exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running.
`.env` files **should be** checked into source control (with the exclusion of `.env*.local`).
@ -1034,22 +967,22 @@ REACT_APP_SECRET_CODE=abcdef
> Note: this feature is **available with `react-scripts@1.0.0` and higher**.
* `.env`: Default.
* `.env.local`: Local overrides. **This file is loaded for all environments except test.**
* `.env.development`, `.env.test`, `.env.production`: Environment-specific settings.
* `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings.
- `.env`: Default.
- `.env.local`: Local overrides. **This file is loaded for all environments except test.**
- `.env.development`, `.env.test`, `.env.production`: Environment-specific settings.
- `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings.
Files on the left have more priority than files on the right:
* `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env`
* `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env`
* `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing)
- `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env`
- `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env`
- `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing)
These variables will act as the defaults if the machine does not explicitly set them.<br>
Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details.
> Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need
these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars).
> these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars).
#### Expanding Environment Variables In `.env`
@ -1078,15 +1011,15 @@ REACT_APP_BAR=$DOMAIN/bar
Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.<br>
Create React App doesnt support decorator syntax at the moment because:
* It is an experimental proposal and is subject to change.
* The current specification version is not officially supported by Babel.
* If the specification changes, we wont be able to write a codemod because we dont use them internally at Facebook.
- It is an experimental proposal and is subject to change.
- The current specification version is not officially supported by Babel.
- If the specification changes, we wont be able to write a codemod because we dont use them internally at Facebook.
However in many cases you can rewrite decorator-based code without decorators just as fine.<br>
Please refer to these two threads for reference:
* [#214](https://github.com/facebookincubator/create-react-app/issues/214)
* [#411](https://github.com/facebookincubator/create-react-app/issues/411)
- [#214](https://github.com/facebookincubator/create-react-app/issues/214)
- [#411](https://github.com/facebookincubator/create-react-app/issues/411)
Create React App will add decorator support when the specification advances to a stable stage.
@ -1106,6 +1039,7 @@ These tutorials will help you to integrate your app with an API backend running
using `fetch()` to access it.
### Node
Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/).
You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo).
@ -1148,9 +1082,9 @@ Keep in mind that `proxy` only has effect in development (with `npm start`), and
The `proxy` option supports HTTP, HTTPS and WebSocket connections.<br>
If the `proxy` option is **not** flexible enough for you, alternatively you can:
* [Configure the proxy yourself](#configuring-the-proxy-manually)
* Enable CORS on your server ([heres how to do it for Express](http://enable-cors.org/server_expressjs.html)).
* Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app.
- [Configure the proxy yourself](#configuring-the-proxy-manually)
- Enable CORS on your server ([heres how to do it for Express](http://enable-cors.org/server_expressjs.html)).
- Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app.
### "Invalid Host Header" Errors After Configuring Proxy
@ -1184,6 +1118,7 @@ We dont recommend this approach.
If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).<br>
You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports.
```js
{
// ...
@ -1202,6 +1137,7 @@ All requests matching this path will be proxies, no exceptions. This includes re
If you need to specify multiple proxies, you may do so by specifying additional entries.
Matches are regular expressions, so that you can use a regexp to match multiple paths.
```js
{
// ...
@ -1301,11 +1237,13 @@ Note that the server will use a self-signed certificate, so your web browser wil
Since Create React App doesnt support server rendering, you might be wondering how to make `<meta>` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this:
```html
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta property="og:title" content="__OG_TITLE__">
<meta property="og:description" content="__OG_DESCRIPTION__">
<meta property="og:title" content="__OG_TITLE__" />
<meta property="og:description" content="__OG_DESCRIPTION__" />
</head>
</html>
```
Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML!
@ -1339,8 +1277,7 @@ Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data
## Running Tests
>Note: this feature is available with `react-scripts@0.3.0` and higher.<br>
>[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)
> Note: this feature is available with `react-scripts@0.3.0` and higher.<br> >[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)
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.
@ -1354,9 +1291,9 @@ We recommend that you use a separate tool for browser end-to-end tests if you ne
Jest will look for test files with any of the following popular naming conventions:
* Files with `.js` suffix in `__tests__` folders.
* Files with `.test.js` suffix.
* Files with `.spec.js` suffix.
- Files with `.js` suffix in `__tests__` folders.
- Files with `.test.js` suffix.
- Files with `.spec.js` suffix.
The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder.
@ -1385,12 +1322,12 @@ To create tests, add `it()` (or `test()`) blocks with the name of the test and i
Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
```js
import sum from './sum';
import sum from './sum'
it('sums numbers', () => {
expect(sum(1, 2)).toEqual(3);
expect(sum(2, 2)).toEqual(4);
});
expect(sum(1, 2)).toEqual(3)
expect(sum(2, 2)).toEqual(4)
})
```
All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).<br>
@ -1403,14 +1340,14 @@ There is a broad spectrum of component testing techniques. They range from a “
Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you havent decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components:
```js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
const div = document.createElement('div')
ReactDOM.render(<App />, div)
})
```
This test mounts a component and makes sure that it didnt throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`.
@ -1434,11 +1371,12 @@ As of Enzyme 3, you will need to install Enzyme along with an Adapter correspond
The adapter will also need to be configured in your [global setup file](#initializing-test-environment):
#### `src/setupTests.js`
```js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
```js
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
```
> Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting.
@ -1446,13 +1384,13 @@ configure({ adapter: new Adapter() });
Now you can write a smoke test with it:
```js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
import React from 'react'
import { shallow } from 'enzyme'
import App from './App'
it('renders without crashing', () => {
shallow(<App />);
});
shallow(<App />)
})
```
Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `<App>` and doesnt go deeper. For example, even if `<App>` itself renders a `<Button>` 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.
@ -1462,16 +1400,16 @@ You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testi
Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
```js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
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>;
const wrapper = shallow(<App />)
const welcome = <h2>Welcome to React</h2>
// expect(wrapper.contains(welcome)).to.equal(true);
expect(wrapper.contains(welcome)).toEqual(true);
});
expect(wrapper.contains(welcome)).toEqual(true)
})
```
All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/en/expect.html).<br>
@ -1498,7 +1436,7 @@ yarn add jest-enzyme
Import it in [`src/setupTests.js`](#initializing-test-environment) to make its matchers available in every test:
```js
import 'jest-enzyme';
import 'jest-enzyme'
```
### Using Third Party Assertion Libraries
@ -1508,8 +1446,8 @@ We recommend that you use `expect()` for assertions and `jest.fn()` for spies. I
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 youd like to port over, you can import them normally like this:
```js
import sinon from 'sinon';
import { expect } from 'chai';
import sinon from 'sinon'
import { expect } from 'chai'
```
and then use them in your tests like you normally do.
@ -1523,12 +1461,13 @@ If your app uses a browser API that you need to mock in your tests or if you jus
For example:
#### `src/setupTests.js`
```js
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
clear: jest.fn(),
}
global.localStorage = localStorageMock
```
@ -1560,6 +1499,7 @@ Note that tests run much slower with coverage so it is recommended to run it sep
The default Jest coverage configuration can be overriden by adding any of the following supported keys to a Jest config in your package.json.
Supported overrides:
- [`collectCoverageFrom`](https://facebook.github.io/jest/docs/en/configuration.html#collectcoveragefrom-array)
- [`coverageReporters`](https://facebook.github.io/jest/docs/en/configuration.html#coveragereporters-array-string)
- [`coverageThreshold`](https://facebook.github.io/jest/docs/en/configuration.html#coveragethreshold-object)
@ -1599,10 +1539,12 @@ When creating a build of your application with `npm run build` linter warnings a
Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
### On CI servers
#### Travis CI
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.
1. Add a `.travis.yml` file to your git repository.
```
language: node_js
node_js:
@ -1614,6 +1556,7 @@ script:
- npm run build
- npm test
```
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.
@ -1622,6 +1565,7 @@ script:
Follow [this article](https://medium.com/@knowbody/circleci-and-zeits-now-sh-c9b7eebcd3c1) to set up CircleCI with a Create React App project.
### On your own environment
##### Windows (cmd.exe)
```cmd
@ -1683,15 +1627,15 @@ If you know that none of your tests depend on [jsdom](https://github.com/tmpvar/
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)
- 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)
- [`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)
Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html).
@ -1714,12 +1658,15 @@ There are various ways to setup a debugger for your Jest tests. We cover debuggi
### Debugging Tests in Chrome
Add the following to the `scripts` section in your project's `package.json`
```json
"scripts": {
"test:debug": "react-scripts --inspect-brk test --runInBand --env=jsdom"
}
```
Place `debugger;` statements in any test and run:
```bash
$ npm run test:debug
```
@ -1727,6 +1674,7 @@ $ npm run test:debug
This will start running your Jest tests, but pause before executing to allow a debugger to attach to the process.
Open the following in Chrome
```
about:inspect
```
@ -1740,6 +1688,7 @@ After opening that link, the Chrome Developer Tools will be displayed. Select `i
Debugging Jest tests is supported out of the box for [Visual Studio Code](https://code.visualstudio.com).
Use the following [`launch.json`](https://code.visualstudio.com/docs/editor/debugging#_launch-configurations) configuration file:
```
{
"version": "0.2.0",
@ -1769,9 +1718,9 @@ Use the following [`launch.json`](https://code.visualstudio.com/docs/editor/debu
Usually, in an app, you have a lot of UI components, and each of them has many different states.
For an example, a simple button component could have following states:
* In a regular state, with a text label.
* In the disabled mode.
* In a loading state.
- In a regular state, with a text label.
- In the disabled mode.
- In a loading state.
Usually, its hard to see these states without running a sample app or some examples.
@ -1801,10 +1750,10 @@ 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/storybooks/storybook)
* [Documentation](https://storybook.js.org/basics/introduction/)
* [Snapshot Testing UI](https://github.com/storybooks/storybook/tree/master/addons/storyshots) with Storybook + addon/storyshot
- Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook)
- [GitHub Repo](https://github.com/storybooks/storybook)
- [Documentation](https://storybook.js.org/basics/introduction/)
- [Snapshot Testing UI](https://github.com/storybooks/storybook/tree/master/addons/storyshots) with Storybook + addon/storyshot
### Getting Started with Styleguidist
@ -1841,8 +1790,8 @@ After that, follow the instructions on the screen.
Learn more about React Styleguidist:
* [GitHub Repo](https://github.com/styleguidist/react-styleguidist)
* [Documentation](https://react-styleguidist.js.org/docs/getting-started.html)
- [GitHub Repo](https://github.com/styleguidist/react-styleguidist)
- [Documentation](https://react-styleguidist.js.org/docs/getting-started.html)
## Publishing Components to npm
@ -1855,9 +1804,9 @@ By default, the production build is a fully functional, offline-first
Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience:
* All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background.
* Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the subway.
* On mobile devices, your app can be added directly to the user's home screen, app icon and all. You can also re-engage users using web **push notifications**. This eliminates the need for the app store.
- All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background.
- Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the subway.
- On mobile devices, your app can be added directly to the user's home screen, app icon and all. You can also re-engage users using web **push notifications**. This eliminates the need for the app store.
The [`sw-precache-webpack-plugin`](https://github.com/goldhand/sw-precache-webpack-plugin)
is integrated into production configuration,
@ -1877,9 +1826,11 @@ If you had previously enabled service workers in your production deployment and
have decided that you would like to disable them for all your existing users,
you can swap out the call to `registerServiceWorker()` in
[`src/index.js`](src/index.js) first by modifying the service worker import:
```javascript
import { unregister } from './registerServiceWorker';
import { unregister } from './registerServiceWorker'
```
and then call `unregister()` instead.
After the user visits a page that has `unregister()`,
the service worker will be uninstalled. Note that depending on how `/service-worker.js` is served,
@ -1903,12 +1854,12 @@ offline-first service worker in a development environment, as it can lead to
frustration when previously cached assets are used and do not include the latest
changes you've made locally.
1. If you *need* to test your offline-first service worker locally, build
1. If you _need_ to test your offline-first service worker locally, build
the application (using `npm run build`) and run a simple http server from your
build directory. After running the build script, `create-react-app` will give
instructions for one way to test your production build locally and the [deployment instructions](#deployment) have
instructions for using other methods. *Be sure to always use an
incognito window to avoid complications with your browser cache.*
instructions for using other methods. _Be sure to always use an
incognito window to avoid complications with your browser cache._
1. If possible, configure your production environment to serve the generated
`service-worker.js` [with HTTP caching disabled](http://stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours).
@ -2019,17 +1970,17 @@ You dont necessarily need a static server in order to run a Create React App
Heres a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
```javascript
const express = require('express');
const path = require('path');
const app = express();
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.static(path.join(__dirname, 'build')))
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
res.sendFile(path.join(__dirname, 'build', 'index.html'))
})
app.listen(9000);
app.listen(9000)
```
The choice of your server software isnt important either. Since Create React App is completely platform-agnostic, theres no need to explicitly use Node.
@ -2098,6 +2049,7 @@ This will let Create React App correctly infer the root path to use in the gener
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">
@ -2250,6 +2202,7 @@ 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",
@ -2279,8 +2232,8 @@ You can configure a custom domain with GitHub Pages by adding a `CNAME` file to
GitHub Pages doesnt 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:
* 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.
* 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 youll 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).
- 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.
- 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 youll 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).
#### Troubleshooting
@ -2400,18 +2353,18 @@ Note that in order to support routers that use HTML5 `pushState` API, you may wa
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
:--- | :---: | :---: | :---
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.
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.
REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebookincubator/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable points to your editors bin folder. You can also set it to `none` to disable it completely.
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.
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.
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`.
| Variable | Development | Production | Usage |
| :------------------ | :--------------------: | :----------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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. |
| 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. |
| REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebookincubator/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH](<https://en.wikipedia.org/wiki/PATH_(variable)>) environment variable points to your editors bin folder. You can also set it to `none` to disable it completely. |
| 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. |
| 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. |
| 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`. |
## Troubleshooting
@ -2420,12 +2373,12 @@ NODE_PATH | :white_check_mark: | :white_check_mark: | Same as [`NODE_PATH` in N
When you save a file while `npm start` is running, the browser should refresh with the updated code.<br>
If this doesnt happen, try one of the following workarounds:
* If your project is in a Dropbox folder, try moving it out.
* If the watcher doesnt see a file called `index.js` and youre 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 [“Adjusting Your Text Editor”](https://webpack.js.org/guides/development/#adjusting-your-text-editor).
* 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).
* 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.
* If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an `.env` file in your project directory if it doesnt 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.
- If your project is in a Dropbox folder, try moving it out.
- If the watcher doesnt see a file called `index.js` and youre 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 [“Adjusting Your Text Editor”](https://webpack.js.org/guides/development/#adjusting-your-text-editor).
- 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).
- 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.
- If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an `.env` file in your project directory if it doesnt 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.
If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659).
@ -2435,9 +2388,9 @@ If you run `npm test` and the console gets stuck after printing `react-scripts t
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)
- [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:
@ -2451,7 +2404,7 @@ You can find [other installation methods](https://facebook.github.io/watchman/do
If this still doesnt help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
There are also reports that _uninstalling_ Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
### `npm run build` exits too early
@ -2474,20 +2427,20 @@ To add a specific Moment.js locale to your bundle, you need to import it explici
For example:
```js
import moment from 'moment';
import 'moment/locale/fr';
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';
import moment from 'moment'
import 'moment/locale/fr'
import 'moment/locale/es'
// ...
moment.locale('fr');
moment.locale('fr')
```
This will only work for locales that have been explicitly imported before.
@ -2500,7 +2453,8 @@ Some third-party packages don't compile their code to ES5 before publishing to n
To resolve this:
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**.
- 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**.
2. Fork the package and publish a corrected version yourself.
@ -2510,7 +2464,7 @@ In the future, we might start automatically compiling incompatible third-party m
## Alternatives to Ejecting
[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/facebookincubator/create-react-app/issues/682).
[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/facebookincubator/create-react-app/issues/682).
## Something Missing?