diff --git a/docs/create-react-app.md b/docs/create-react-app.md index 57750284..479d632a 100644 --- a/docs/create-react-app.md +++ b/docs/create-react-app.md @@ -13,6 +13,7 @@ You can find the most recent version of this guide [here](https://github.com/fac - [npm test](#npm-test) - [npm run build](#npm-run-build) - [npm run eject](#npm-run-eject) +- [Supported Browsers](#supported-browsers) - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) @@ -34,11 +35,13 @@ You can find the most recent version of this guide [here](https://github.com/fac - [Adding Bootstrap](#adding-bootstrap) - [Using a Custom Theme](#using-a-custom-theme) - [Adding Flow](#adding-flow) +- [Adding a Router](#adding-a-router) - [Adding Custom Environment Variables](#adding-custom-environment-variables) - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) - [Can I Use Decorators?](#can-i-use-decorators) +- [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) - [Integrating with an API Backend](#integrating-with-an-api-backend) - [Node](#node) - [Ruby on Rails](#ruby-on-rails) @@ -64,10 +67,15 @@ You can find the most recent version of this guide [here](https://github.com/fac - [Disabling jsdom](#disabling-jsdom) - [Snapshot Testing](#snapshot-testing) - [Editor Integration](#editor-integration) +- [Debugging Tests](#debugging-tests) + - [Debugging Tests in Chrome](#debugging-tests-in-chrome) + - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) - [Developing Components in Isolation](#developing-components-in-isolation) - [Getting Started with Storybook](#getting-started-with-storybook) - [Getting Started with Styleguidist](#getting-started-with-styleguidist) +- [Publishing Components to npm](#publishing-components-to-npm) - [Making a Progressive Web App](#making-a-progressive-web-app) + - [Opting Out of Caching](#opting-out-of-caching) - [Offline-First Considerations](#offline-first-considerations) - [Progressive Web App Metadata](#progressive-web-app-metadata) - [Analyzing the Bundle Size](#analyzing-the-bundle-size) @@ -80,7 +88,6 @@ You can find the most recent version of this guide [here](https://github.com/fac - [Firebase](#firebase) - [GitHub Pages](#github-pages) - [Heroku](#heroku) - - [Modulus](#modulus) - [Netlify](#netlify) - [Now](#now) - [S3 and CloudFront](#s3-and-cloudfront) @@ -91,7 +98,9 @@ You can find the most recent version of this guide [here](https://github.com/fac - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) - [`npm run build` exits too early](#npm-run-build-exits-too-early) - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) + - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) - [Moment.js locales are missing](#momentjs-locales-are-missing) +- [Alternatives to Ejecting](#alternatives-to-ejecting) - [Something Missing?](#something-missing) ## Updating to New Releases @@ -189,6 +198,12 @@ Instead, it will copy all the configuration files and the transitive dependencie You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. +## Supported Browsers + +By default, the generated project uses the latest version of React. + +You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers. + ## Supported Language Features and Polyfills This project supports a superset of the latest JavaScript standard.
@@ -198,12 +213,12 @@ In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, * [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) (stage 2 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-). -While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. +While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: @@ -213,6 +228,8 @@ Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia 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. +Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to. + ## Syntax Highlighting in the Editor To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. @@ -242,9 +259,11 @@ If you want to enforce a coding style for your project, consider using [Prettier ## Debugging in the Editor -**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.** +**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** + +Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. -Visual Studio Code supports debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. +### Visual Studio Code You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. @@ -259,16 +278,30 @@ Then add the block below to your `launch.json` file and put it inside the `.vsco "request": "launch", "url": "http://localhost:3000", "webRoot": "${workspaceRoot}/src", - "userDataDir": "${workspaceRoot}/.vscode/chrome", "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. +Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). + +### WebStorm + +You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed. + +In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration. + +>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`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm. + +The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. + ## Formatting Code Automatically Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/). @@ -315,9 +348,9 @@ Next we add a 'lint-staged' field to the `package.json`, for example: "scripts": { ``` -Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time. +Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx,json,css}"` to format your entire project for the first time. -Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page. +Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page. ## Changing the Page `` @@ -445,6 +478,8 @@ You can also use it with `async` / `await` syntax if you prefer it. If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app). +Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. + ## Adding a Stylesheet This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: @@ -583,7 +618,8 @@ Then we can change `start` and `build` scripts to include the CSS preprocessor c - "build": "react-scripts build", + "start-js": "react-scripts start", + "start": "npm-run-all -p watch-css start-js", -+ "build": "npm run build-css && react-scripts build", ++ "build-js": "react-scripts build", ++ "build": "npm-run-all build-css build-js", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } @@ -785,6 +821,26 @@ In the future we plan to integrate it into Create React App even more closely. To learn more about Flow, check out [its documentation](https://flowtype.org/). +## Adding a Router + +Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/) is the most popular one. + +To add it, run: + +```sh +npm install --save react-router-dom +``` + +Alternatively you may use `yarn`: + +```sh +yarn add react-router-dom +``` + +To try it, delete all the code in `src/App.js` and replace it with any of the examples on its website. The [Basic Example](https://reacttraining.com/react-router/web/example/basic) is a good place to get started. + +Note that [you may need to configure your production server to support client-side routing](#serving-apps-with-client-side-routing) before deploying your app. + ## Adding Custom Environment Variables >Note: this feature is available with `react-scripts@0.2.3` and higher. @@ -871,10 +927,16 @@ life of the shell session. #### Windows (cmd.exe) ```cmd -set REACT_APP_SECRET_CODE=abcdef&&npm start +set "REACT_APP_SECRET_CODE=abcdef" && npm start ``` -(Note: the lack of whitespace is intentional.) +(Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) + +#### Windows (Powershell) + +```Powershell +($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) +``` #### Linux, macOS (Bash) @@ -891,10 +953,11 @@ 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`). -#### What other `.env` files are can be used? +#### What other `.env` files can be used? >Note: this feature is **available with `react-scripts@1.0.0` and higher**. @@ -915,6 +978,28 @@ Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) f >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). +#### Expanding Environment Variables In `.env` + +>Note: this feature is available with `react-scripts@1.1.0` and higher. + +Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). + +For example, to get the environment variable `npm_package_version`: + +``` +REACT_APP_VERSION=$npm_package_version +# also works: +# REACT_APP_VERSION=${npm_package_version} +``` + +Or expand variables local to the current `.env` file: + +``` +DOMAIN=www.example.com +REACT_APP_FOO=$DOMAIN/foo +REACT_APP_BAR=$DOMAIN/bar +``` + ## Can I Use Decorators? Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.<br> @@ -932,6 +1017,16 @@ Please refer to these two threads for reference: Create React App will add decorator support when the specification advances to a stable stage. +## Fetching Data with AJAX Requests + +React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like [axios](https://github.com/axios/axios) or the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provided by the browser. Conveniently, Create React App includes a polyfill for `fetch()` so you can use it without worrying about the browser support. + +The global `fetch` function allows to easily makes AJAX requests. It takes in a URL as an input and returns a `Promise` that resolves to a `Response` object. You can find more information about `fetch` [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). + +This project also includes a [Promise polyfill](https://github.com/then/promise) which provides a full implementation of Promises/A+. A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises [here](https://www.promisejs.org/) and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Both axios and `fetch()` use Promises under the hood. You can also use the [`async / await`](https://davidwalsh.name/async-await) syntax to reduce the callback nesting. + +You can learn more about making AJAX requests from React components in [the FAQ entry on the React website](https://reactjs.org/docs/faq-ajax.html). + ## Integrating with an API Backend These tutorials will help you to integrate your app with an API backend running on another port, @@ -967,7 +1062,7 @@ To tell the development server to proxy any unknown requests to your API server "proxy": "http://localhost:4000", ``` -This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. +This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will **only** attempt to send requests without `text/html` in its `Accept` header to the proxy. Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: @@ -1033,7 +1128,7 @@ You may also specify any configuration value [`http-proxy-middleware`](https://g All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. If you need to specify multiple proxies, you may do so by specifying additional entries. -You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. +Matches are regular expressions, so that you can use a regexp to match multiple paths. ```js { // ... @@ -1054,12 +1149,12 @@ You may also narrow down matches using `*` and/or `**`, to match the path exactl // ... }, // Matches /bar/abc.html but not /bar/sub/def.html - "/bar/*.html": { + "/bar/[^/]*[.]html": { "target": "<url_3>", // ... }, // Matches /baz/abc.html and /baz/sub/def.html - "/baz/**/*.html": { + "/baz/.*/.*[.]html": { "target": "<url_4>" // ... } @@ -1112,6 +1207,12 @@ To do this, set the `HTTPS` environment variable to `true`, then start the dev s set HTTPS=true&&npm start ``` +#### Windows (Powershell) + +```Powershell +($env:HTTPS = $true) -and (npm start) +``` + (Note: the lack of whitespace is intentional.) #### Linux, macOS (Bash) @@ -1140,7 +1241,7 @@ If you use a Node server, you can even share the route matching logic between th ## Pre-Rendering into Static HTML Files -If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. +If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) or [react-snap](https://github.com/stereobooster/react-snap) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. @@ -1219,8 +1320,8 @@ it('sums numbers', () => { }); ``` -All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).<br> -You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. +All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).<br> +You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies” or mock functions. ### Testing Components @@ -1239,23 +1340,37 @@ it('renders without crashing', () => { }); ``` -This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. +This test mounts a component and makes sure that it didn’t 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`. When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: ```sh -npm install --save enzyme react-test-renderer +npm install --save enzyme enzyme-adapter-react-16 react-test-renderer ``` Alternatively you may use `yarn`: ```sh -yarn add enzyme react-test-renderer +yarn add enzyme enzyme-adapter-react-16 react-test-renderer ``` -You can write a smoke test with it too: +As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.) + +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() }); +``` + +>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. + +Now you can write a smoke test with it: ```js import React from 'react'; @@ -1286,10 +1401,10 @@ it('renders welcome message', () => { }); ``` -All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).<br> +All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/en/expect.html).<br> Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below. -Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written simpler with jest-enzyme. +Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written more simply with jest-enzyme. ```js expect(wrapper).toContainReact(welcome) @@ -1344,6 +1459,15 @@ const localStorageMock = { global.localStorage = localStorageMock ``` +>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, so you should manually create the property `setupTestFrameworkScriptFile` in the configuration for Jest, something like the following: + +>```js +>"jest": { +> // ... +> "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js" +> } +> ``` + ### Focusing and Excluding Tests You can replace `it()` with `xit()` to temporarily exclude a test from being executed.<br> @@ -1358,6 +1482,41 @@ Run `npm test -- --coverage` (note extra `--` in the middle) to include a covera Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow. +#### Configuration + +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) + - [`snapshotSerializers`](https://facebook.github.io/jest/docs/en/configuration.html#snapshotserializers-array-string) + +Example package.json: + +```json +{ + "name": "your-package", + "jest": { + "collectCoverageFrom" : [ + "src/**/*.{js,jsx}", + "!<rootDir>/node_modules/", + "!<rootDir>/path/to/dir/" + ], + "coverageThreshold": { + "global": { + "branches": 90, + "functions": 90, + "lines": 90, + "statements": 90 + } + }, + "coverageReporters": ["text"], + "snapshotSerializers": ["my-serializer-module"] + } +} +``` + ### Continuous Integration By default `npm test` runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called `CI`. @@ -1379,8 +1538,8 @@ cache: directories: - node_modules script: - - npm test - 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. @@ -1402,6 +1561,16 @@ set CI=true&&npm run build (Note: the lack of whitespace is intentional.) +##### Windows (Powershell) + +```Powershell +($env:CI = $true) -and (npm test) +``` + +```Powershell +($env:CI = $true) -and (npm run build) +``` + ##### Linux, macOS (Bash) ```bash @@ -1463,6 +1632,65 @@ If you use [Visual Studio Code](https://code.visualstudio.com), there is a [Jest ![VS Code Jest Preview](https://cloud.githubusercontent.com/assets/49038/20795349/a032308a-b7c8-11e6-9b34-7eeac781003f.png) +## Debugging Tests + +There are various ways to setup a debugger for your Jest tests. We cover debugging in Chrome and [Visual Studio Code](https://code.visualstudio.com/). + +>Note: debugging tests requires Node 8 or higher. + +### 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 +``` + +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 +``` + +After opening that link, the Chrome Developer Tools will be displayed. Select `inspect` on your process and a breakpoint will be set at the first line of the react script (this is done simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack. + +>Note: the --runInBand cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time. + +### Debugging Tests in Visual Studio Code + +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", + "configurations": [ + { + "name": "Debug CRA Tests", + "type": "node", + "request": "launch", + "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts", + "args": [ + "test", + "--runInBand", + "--no-cache", + "--env=jsdom" + ], + "cwd": "${workspaceRoot}", + "protocol": "inspector", + "console": "integratedTerminal", + "internalConsoleOptions": "neverOpen" + } + ] +} +``` + ## Developing Components in Isolation Usually, in an app, you have a lot of UI components, and each of them has many different states. @@ -1543,6 +1771,10 @@ Learn more about React Styleguidist: * [GitHub Repo](https://github.com/styleguidist/react-styleguidist) * [Documentation](https://react-styleguidist.js.org/docs/getting-started.html) +## Publishing Components to npm + +Create React App doesn't provide any built-in functionality to publish a component to npm. If you're ready to extract a component from your project so other people can use it, we recommend moving it to a separate directory outside of your project and then using a tool like [nwb](https://github.com/insin/nwb#react-components-and-libraries) to prepare it for publishing. + ## Making a Progressive Web App By default, the production build is a fully functional, offline-first @@ -1551,7 +1783,7 @@ 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. + * 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) @@ -1562,16 +1794,23 @@ The service worker will use a [cache-first strategy](https://developers.google.c for handling all requests for local assets, including the initial HTML, ensuring that your web app is reliably fast, even on a slow or unreliable network. +### Opting Out of Caching + If you would prefer not to enable service workers prior to your initial -production deployment, then remove the call to `serviceWorkerRegistration.register()` +production deployment, then remove the call to `registerServiceWorker()` from [`src/index.js`](src/index.js). 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 `serviceWorkerRegistration.register()` in -[`src/index.js`](src/index.js) with a call to `serviceWorkerRegistration.unregister()`. -After the user visits a page that has `serviceWorkerRegistration.unregister()`, -the service worker will be uninstalled. +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'; +``` +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, +it may take up to 24 hours for the cache to be invalidated. ### Offline-First Considerations @@ -1671,16 +1910,6 @@ Then in `package.json`, add the following line to `scripts`: "test": "react-scripts test --env=jsdom", ``` ->**Note:** -> ->This doesn't quite work on Windows because it doesn't automatically expand `*` in the filepath. For now, the workaround is to look at the full hashed filename in `build/static/js` (e.g. `main.89b7e95a.js`) and copy it into `package.json` when you're running the analyzer. For example: -> ->```diff ->+ "analyze": "source-map-explorer build/static/js/main.89b7e95a.js", ->``` -> ->Unfortunately it will be different after every build. You can express support for fixing this on Windows [in this issue](https://github.com/danvk/source-map-explorer/issues/52). - Then to analyze the bundle run the production build then run the analyze script. @@ -1691,7 +1920,7 @@ npm run analyze ## Deployment -`npm run build` creates a `build` directory with a production build of your app. Set up your favourite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main.<hash>.js` are served with the contents of the `/static/js/main.<hash>.js` file. +`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. ### Static Server @@ -1775,6 +2004,12 @@ service worker navigation routing can be configured or disabled by and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp) options of the `SWPreachePlugin` [configuration](../config/webpack.config.prod.js). +When users install your app to the homescreen of their device the default configuration will make a shortcut to `/index.html`. This may not work for client-side routers which expect the app to be served from `/`. Edit the web app manifest at [`public/manifest.json`](public/manifest.json) and change `start_url` to match the required URL scheme, for example: + +```js + "start_url": ".", +``` + ### Building for Relative Paths By default, Create React App produces a build assuming your app is hosted at the server root.<br> @@ -1786,6 +2021,15 @@ To override this, specify the `homepage` in your `package.json`, for example: This will let Create React App correctly infer the root path to use in the generated HTML file. +**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"> +``` + #### Serving the Same Build from Different Paths >Note: this feature is available with `react-scripts@0.9.0` and higher. @@ -1798,11 +2042,13 @@ If you are not using the HTML5 `pushState` history API or not using client-side 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. -### Azure +### [Azure](https://azure.microsoft.com/) -See [this](https://medium.com/@to_pe/deploying-create-react-app-on-microsoft-azure-c0f6686a4321) blog post on how to deploy your React app to [Microsoft Azure](https://azure.microsoft.com/). +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. -### Firebase +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. + +### [Firebase](https://firebase.google.com/) 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. @@ -1843,6 +2089,18 @@ Then run the `firebase init` command from your project’s root. You need to cho ✔ Firebase initialization complete! ``` +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/facebookincubator/create-react-app/issues/2440)). It should be added inside `"hosting"` key like next: + +``` +{ + "hosting": { + ... + "headers": [ + {"source": "/service-worker.js", "headers": [{"key": "Cache-Control", "value": "no-cache"}]} + ] + ... +``` + Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`. ```sh @@ -1863,7 +2121,7 @@ Now, after you create a production build with `npm run build`, you can deploy it For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup). -### GitHub Pages +### [GitHub Pages](https://pages.github.com/) >Note: this feature is available with `react-scripts@0.2.0` and higher. @@ -1872,12 +2130,18 @@ For more information see [Add Firebase to your JavaScript Project](https://fireb **The step below is important!**<br> **If you skip it, your app will not deploy correctly.** -Open your `package.json` and add a `homepage` field: +Open your `package.json` and add a `homepage` field for your project: -```js +```json "homepage": "https://myusername.github.io/my-app", ``` +or for a GitHub user page: + +```json + "homepage": "https://myusername.github.io", +``` + Create React App uses the `homepage` field to determine the root URL in the built HTML file. #### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json` @@ -1908,6 +2172,18 @@ Add the following scripts in your `package.json`: The `predeploy` script will run automatically before `deploy` is run. +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", +``` + #### Step 3: Deploy the site by running `npm run deploy` Then run: @@ -1933,7 +2209,17 @@ GitHub Pages doesn’t support routers that use the HTML5 `pushState` history AP * 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 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). -### Heroku +#### 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` + +### [Heroku](https://www.heroku.com/) Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).<br> You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration). @@ -1971,16 +2257,12 @@ remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/ 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`. -### Modulus - -See the [Modulus blog post](http://blog.modulus.io/deploying-react-apps-on-modulus) on how to deploy your react app to Modulus. - -### Netlify +### [Netlify](https://www.netlify.com/) **To do a manual deploy to Netlify’s CDN:** ```sh -npm install netlify-cli +npm install netlify-cli -g netlify deploy ``` @@ -1992,7 +2274,8 @@ With this setup Netlify will build and deploy when you push to git or open a pul 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` +3. Set `yarn build` as the build command and `build` as the publish directory +4. Click `Deploy site` **Support for client-side routing:** @@ -2004,9 +2287,9 @@ To support `pushState`, make sure to create a `public/_redirects` file with the When you build the project, Create React App will place the `public` folder contents into the build output. -### Now +### [Now](https://zeit.co/now) -[now](https://zeit.co/now) offers a zero-configuration single-command deployment. You can use `now` to deploy your app for free. +Now offers a zero-configuration single-command deployment. You can use `now` to deploy your app for free. 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`. @@ -2024,11 +2307,11 @@ When you build the project, Create React App will place the `public` folder cont Details are available in [this article.](https://zeit.co/blog/unlimited-static) -### S3 and CloudFront +### [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/) -See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-to-s3-or-cloudfront-48dae4ce0af) on how to deploy your React app to Amazon Web Services [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/). +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. -### Surge +### [Surge](https://surge.sh/) 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. @@ -2052,7 +2335,10 @@ PORT | :white_check_mark: | :x: | By default, the development web server will at 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 editor’s bin folder. +REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebookincubator/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable points to your editor’s bin folder. 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 @@ -2065,7 +2351,7 @@ If this doesn’t happen, try one of the following workarounds: * If the watcher doesn’t see a file called `index.js` and you’re referencing it by the folder name, you [need to restart the watcher](https://github.com/facebookincubator/create-react-app/issues/1164) due to a Webpack bug. * Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in [“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://webpack.github.io/docs/troubleshooting.html#not-enough-watchers) to allow more watchers. +* 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 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. If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659). @@ -2133,6 +2419,26 @@ moment.locale('fr'); This will only work for locales that have been explicitly imported before. +### `npm run build` fails to minify + +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. + +<br> +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**. + +2. Fork the package and publish a corrected version yourself. + +3. If the dependency is small enough, copy it to your `src/` folder and treat it as application code. + +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. + +## 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). + ## Something Missing? If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebookincubator/create-react-app/issues) or [contribute some!](https://github.com/facebookincubator/create-react-app/edit/master/packages/react-scripts/template/README.md) diff --git a/package.json b/package.json index 52a44f2a..ced0ba52 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "react-metrics-graphics": "1.0.2", "react-refetch": "1.0.4", "react-router-dom": "4.2.2", - "react-scripts": "1.1.1", + "react-scripts": "1.1.4", "react-spinkit": "3.0.0" }, "devDependencies": { diff --git a/yarn.lock b/yarn.lock index 967fcc28..3bf05cf1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2620,9 +2620,9 @@ detect-node@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.0.3.tgz#a2033c09cc8e158d37748fbde7507832bd6ce127" -detect-port-alt@1.1.5: - version "1.1.5" - resolved "https://registry.yarnpkg.com/detect-port-alt/-/detect-port-alt-1.1.5.tgz#a1aa8fc805a4a5df9b905b7ddc7eed036bcce889" +detect-port-alt@1.1.6: + version "1.1.6" + resolved "https://registry.yarnpkg.com/detect-port-alt/-/detect-port-alt-1.1.6.tgz#24707deabe932d4a3cf621302027c2b266568275" dependencies: address "^1.0.1" debug "^2.6.0" @@ -7017,15 +7017,15 @@ rc@^1.0.1, rc@^1.1.6, rc@^1.1.7: minimist "^1.2.0" strip-json-comments "~2.0.1" -react-dev-utils@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/react-dev-utils/-/react-dev-utils-5.0.0.tgz#425ac7c9c40c2603bc4f7ab8836c1406e96bb473" +react-dev-utils@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/react-dev-utils/-/react-dev-utils-5.0.1.tgz#1f396e161fe44b595db1b186a40067289bf06613" dependencies: address "1.0.3" babel-code-frame "6.26.0" chalk "1.1.3" cross-spawn "5.1.0" - detect-port-alt "1.1.5" + detect-port-alt "1.1.6" escape-string-regexp "1.0.5" filesize "3.5.11" global-modules "1.0.0" @@ -7096,9 +7096,9 @@ react-router@^4.2.0: prop-types "^15.5.4" warning "^3.0.0" -react-scripts@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/react-scripts/-/react-scripts-1.1.1.tgz#279d449f7311fed910506987a1ade014027788a8" +react-scripts@1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/react-scripts/-/react-scripts-1.1.4.tgz#d5c230e707918d6dd2d06f303b10f5222d017c88" dependencies: autoprefixer "7.1.6" babel-core "6.26.0" @@ -7129,7 +7129,8 @@ react-scripts@1.1.1: postcss-loader "2.0.8" promise "8.0.1" raf "3.4.0" - react-dev-utils "^5.0.0" + react-dev-utils "^5.0.1" + resolve "1.6.0" style-loader "0.19.0" sw-precache-webpack-plugin "0.11.4" url-loader "0.6.2" @@ -7579,6 +7580,12 @@ resolve@1.1.7: version "1.1.7" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" +resolve@1.6.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.6.0.tgz#0fbd21278b27b4004481c395349e7aba60a9ff5c" + dependencies: + path-parse "^1.0.5" + resolve@^1.3.2, resolve@^1.5.0: version "1.5.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.5.0.tgz#1f09acce796c9a762579f31b2c1cc4c3cddf9f36"