diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..6313b56c578 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index f51aebeac2d..f0e8f10f061 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,2 +1,2 @@ packages/ @ianschmitz @iansu @mrmckeb @petetnt -docusaurus/ @amyrlam @iansu +docusaurus/ @ianschmitz @iansu @mrmckeb diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index 147ea1dc458..e547baf9d3f 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -4,7 +4,7 @@ about: Get help with Create React App labels: 'needs triage' --- -If you have a general question about Create React App or about building an app with Create React App we encourage you to post on our Spectrum community instead of this issue tracker. The maintainers and other community members can provide help and answer your questions there: https://spectrum.chat/create-react-app +If you have a general question about Create React App or about building an app with Create React App we encourage you to post in GitHub Discussions instead of this issue tracker. The maintainers and other community members can provide help and answer your questions there: https://github.com/facebook/create-react-app/discussions If you're looking for general information on using React, the React docs have a list of resources: https://reactjs.org/community/support.html diff --git a/.github/stale.yml b/.github/stale.yml index 9dafb647ef1..91807e989b9 100644 --- a/.github/stale.yml +++ b/.github/stale.yml @@ -9,20 +9,20 @@ daysUntilClose: 5 # Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable exemptLabels: - - "contributions: claimed" - - "contributions: up for grabs!" - - "good first issue" - - "issue: announcement" - - "issue: bug" - - "issue: needs investigation" - - "issue: proposal" - - "tag: breaking change" - - "tag: bug fix" - - "tag: documentation" - - "tag: enhancement" - - "tag: internal" - - "tag: new feature" - - "tag: underlying tools" + - 'contributions: claimed' + - 'contributions: up for grabs!' + - 'good first issue' + - 'issue: announcement' + - 'issue: bug' + - 'issue: needs investigation' + - 'issue: proposal' + - 'tag: breaking change' + - 'tag: bug fix' + - 'tag: documentation' + - 'tag: enhancement' + - 'tag: internal' + - 'tag: new feature' + - 'tag: underlying tools' # Set to true to ignore issues in a project (defaults to false) exemptProjects: true diff --git a/CHANGELOG.md b/CHANGELOG.md index e78e28f3f06..91d4582dd87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,39 @@ +## 3.4.3 (2020-08-12) + +v3.4.2 release bumps `terser-webpack-plugin` to a version for which `npm audit` does not report a vulnerability. Note that **this vulnerability did not affect Create React App projects**, so this change is only necessary to satisfy auditing tools. + +### Migrating from 3.4.2 to 3.4.3 + +Inside any created project that has not been ejected, run: + +```sh +npm install --save --save-exact react-scripts@3.4.3 +``` + +or + +```sh +yarn add --exact react-scripts@3.4.3 +``` + +## 3.4.2 (2020-08-11) + +v3.4.2 release bumps `webpack-dev-server` to a version for which `npm audit` does not report a vulnerability. Note that **this vulnerability did not affect Create React App projects**, so this change is only necessary to satisfy auditing tools. + +### Migrating from 3.4.1 to 3.4.2 + +Inside any created project that has not been ejected, run: + +```sh +npm install --save --save-exact react-scripts@3.4.2 +``` + +or + +```sh +yarn add --exact react-scripts@3.4.2 +``` + ## 3.4.1 (2020-03-20) v3.4.1 is a maintenance release that includes minor bug fixes and documentation updates including upgrading Babel to fix a bug in the 7.8 release line. This release also brings support for TypeScript 3.8. diff --git a/README.md b/README.md index 55e8b891f20..6db44574976 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Create React App [![Build Status](https://dev.azure.com/facebook/create-react-app/_apis/build/status/facebook.create-react-app?branchName=master)](https://dev.azure.com/facebook/create-react-app/_build/latest?definitionId=1&branchName=master) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-green.svg)](https://github.com/facebook/create-react-app/blob/master/CONTRIBUTING.md) +Logo + Create React apps with no build configuration. - [Creating an App](#creating-an-app) – How to create a new app. @@ -7,7 +9,7 @@ Create React apps with no build configuration. Create React App works on macOS, Windows, and Linux.
If something doesn’t work, please [file an issue](https://github.com/facebook/create-react-app/issues/new).
-If you have questions or need help, please ask in our [Spectrum](https://spectrum.chat/create-react-app) community. +If you have questions or need help, please ask in [GitHub Discussions](https://github.com/facebook/create-react-app/discussions). ## Quick Overview @@ -17,7 +19,7 @@ cd my-app npm start ``` -If you've previously installed `create-react-app` globally via `npm install -g create-react-app`, we recommend you uninstall the package using `npm uninstall -g create-react-app` to ensure that npx always uses the latest version. +If you've previously installed `create-react-app` globally via `npm install -g create-react-app`, we recommend you uninstall the package using `npm uninstall -g create-react-app` or `yarn global remove create-react-app` to ensure that npx always uses the latest version. _([npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) comes with npm 5.2+ and higher, see [instructions for older npm versions](https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f))_ @@ -175,9 +177,9 @@ Here are a few common cases where you might want to try something else: - If you need to **publish a React component**, [nwb](https://github.com/insin/nwb) can [also do this](https://github.com/insin/nwb#react-components-and-libraries), as well as [Neutrino's react-components preset](https://neutrino.js.org/packages/react-components/). -- If you want to do **server rendering** with React and Node.js, check out [Next.js](https://github.com/zeit/next.js/) or [Razzle](https://github.com/jaredpalmer/razzle). Create React App is agnostic of the backend, and only produces static HTML/JS/CSS bundles. +- If you want to do **server rendering** with React and Node.js, check out [Next.js](https://nextjs.org/) or [Razzle](https://github.com/jaredpalmer/razzle). Create React App is agnostic of the backend, and only produces static HTML/JS/CSS bundles. -- If your website is **mostly static** (for example, a portfolio or a blog), consider using [Gatsby](https://www.gatsbyjs.org/) instead. Unlike Create React App, it pre-renders the website into HTML at the build time. +- If your website is **mostly static** (for example, a portfolio or a blog), consider using [Gatsby](https://www.gatsbyjs.org/) or [Next.js](https://nextjs.org/). Unlike Create React App, Gatsby pre-renders the website into HTML at build time. Next.js supports both server rendering and pre-rendering. - Finally, if you need **more customization**, check out [Neutrino](https://neutrino.js.org/) and its [React preset](https://neutrino.js.org/packages/react/). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000000..1c4112b6d4c --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Reporting Security Issues + +If you believe you have found a security vulnerability in Create React App, we encourage you to let us know right away. We will investigate all legitimate reports and do our best to quickly fix the problem. + +Please refer to the following page for our responsible disclosure policy, reward guidelines, and those things that should not be reported: + +https://www.facebook.com/whitehat diff --git a/azure-pipelines-test-job.yml b/azure-pipelines-test-job.yml index e3b9d92b669..116d2f87e23 100644 --- a/azure-pipelines-test-job.yml +++ b/azure-pipelines-test-job.yml @@ -1,40 +1,38 @@ -# -# Azure Pipelines job for building and testing create-react-app on Linux, Windows, and macOS. -# - -parameters: - name: '' - testScript: '' - configurations: - LinuxNode10: { vmImage: 'ubuntu-16.04', nodeVersion: 10.x } - LinuxNode12: { vmImage: 'ubuntu-16.04', nodeVersion: 12.x } - # WindowsNode10: { vmImage: 'windows-latest', nodeVersion: 10.x } - # WindowsNode12: { vmImage: 'windows-latest', nodeVersion: 12.x } - -jobs: - - job: ${{ parameters.name }} - strategy: - matrix: - ${{ insert }}: ${{ parameters.configurations }} - pool: - vmImage: $(vmImage) - steps: - - script: | - git config --global core.autocrlf false - git config --global user.name "Create React App" - git config --global user.email "cra@email.com" - displayName: 'Initialize Git config' - - - checkout: self - path: create-react-app - - - task: NodeTool@0 - inputs: - versionSpec: $(nodeVersion) - displayName: 'Install Node.js' - - - script: yarn --frozen-lockfile - displayName: 'Run yarn' - - - bash: ${{ parameters.testScript }} - displayName: 'Run tests' +# +# Azure Pipelines job for building and testing create-react-app on Linux, Windows, and macOS. +# + +parameters: + name: '' + testScript: '' + configurations: + LinuxNode10: { vmImage: 'ubuntu-16.04', nodeVersion: 10.x } + LinuxNode12: { vmImage: 'ubuntu-16.04', nodeVersion: 12.x } + +jobs: + - job: ${{ parameters.name }} + strategy: + matrix: + ${{ insert }}: ${{ parameters.configurations }} + pool: + vmImage: $(vmImage) + steps: + - script: | + git config --global core.autocrlf false + git config --global user.name "Create React App" + git config --global user.email "cra@email.com" + displayName: 'Initialize Git config' + + - checkout: self + path: create-react-app + + - task: NodeTool@0 + inputs: + versionSpec: $(nodeVersion) + displayName: 'Install Node.js' + + - script: yarn --frozen-lockfile + displayName: 'Run yarn' + + - bash: ${{ parameters.testScript }} + displayName: 'Run tests' diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 6f9f49df877..3c89363208b 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,79 +1,77 @@ -# -# Azure Pipelines configuration for building and testing create-react-app on Linux, Windows, and macOS. -# - -trigger: - - master - -variables: - CI: true - # Overrides the Yarn and NPM cache directories so they are on the same drive as the source. This helps improve build performance on Windows hosted agents. - YARN_CACHE_FOLDER: $(Build.SourcesDirectory)/../yarn-cache - NPM_CONFIG_CACHE: $(Build.SourcesDirectory)/../npm-cache - # Sets TEMP to be on the same drive as the cloned source on Windows. This avoids test scripts that "cd" into a directory under TEMP from failing because this directory is on a different drive from the current directory. - VSTS_OVERWRITE_TEMP: True - # Override Verdaccio package to use. This is temporary and is needed to avoid socket timeouts on hosted Windows agent (on Azure). This also changes Verdaccio to return a 503 (service unavailable) instead of a 404 (not found) when the connection to the uplink timesout. - VERDACCIO_PACKAGE: https://github.com/willsmythe/verdaccio/releases/download/create-react-app/verdaccio-4.0.0-alpha.8.tgz - CRA_INTERNAL_TEST: true - -# ****************************************************************************** -# Simple test suite -# ****************************************************************************** -jobs: - - template: azure-pipelines-test-job.yml - parameters: - name: Simple - testScript: tasks/e2e-simple.sh - - # ****************************************************************************** - # Installs test suite - # ****************************************************************************** - - template: azure-pipelines-test-job.yml - parameters: - name: Installs - testScript: tasks/e2e-installs.sh - - # ****************************************************************************** - # Kitchensink test suite - # ****************************************************************************** - - template: azure-pipelines-test-job.yml - parameters: - name: Kitchensink - testScript: tasks/e2e-kitchensink.sh - - # ****************************************************************************** - # Kitchensink Eject test suite - # ****************************************************************************** - - template: azure-pipelines-test-job.yml - parameters: - name: KitchensinkEject - testScript: tasks/e2e-kitchensink-eject.sh - - # ****************************************************************************** - # Behavior test suite - # ****************************************************************************** - - template: azure-pipelines-test-job.yml - parameters: - name: Behavior - testScript: tasks/e2e-behavior.sh - configurations: - LinuxNode10: { vmImage: 'ubuntu-16.04', nodeVersion: 10.x } - LinuxNode12: { vmImage: 'ubuntu-16.04', nodeVersion: 12.x } - # WindowsNode10: { vmImage: 'windows-latest', nodeVersion: 10.x } - # WindowsNode12: { vmImage: 'windows-latest', nodeVersion: 12.x } - MacNode10: { vmImage: 'macOS-latest', nodeVersion: 10.x } - MacNode12: { vmImage: 'macOS-latest', nodeVersion: 12.x } - - # ****************************************************************************** - # Old Node test suite - # ****************************************************************************** - - job: OldNode - pool: - vmImage: ubuntu-latest - steps: - - task: NodeTool@0 - inputs: - versionSpec: 8.x - displayName: 'Install Node.js 8.x' - - bash: tasks/e2e-old-node.sh - displayName: 'Run tests' +# +# Azure Pipelines configuration for building and testing create-react-app on Linux, Windows, and macOS. +# + +trigger: + - master + +variables: + CI: true + # Overrides the Yarn and NPM cache directories so they are on the same drive as the source. This helps improve build performance on Windows hosted agents. + YARN_CACHE_FOLDER: $(Build.SourcesDirectory)/../yarn-cache + NPM_CONFIG_CACHE: $(Build.SourcesDirectory)/../npm-cache + # Sets TEMP to be on the same drive as the cloned source on Windows. This avoids test scripts that "cd" into a directory under TEMP from failing because this directory is on a different drive from the current directory. + VSTS_OVERWRITE_TEMP: True + CRA_INTERNAL_TEST: true + +# ****************************************************************************** +# Simple test suite +# ****************************************************************************** +jobs: + - template: azure-pipelines-test-job.yml + parameters: + name: Simple + testScript: tasks/e2e-simple.sh + + # ****************************************************************************** + # Installs test suite + # ****************************************************************************** + - template: azure-pipelines-test-job.yml + parameters: + name: Installs + testScript: tasks/e2e-installs.sh + + # ****************************************************************************** + # Kitchensink test suite + # ****************************************************************************** + - template: azure-pipelines-test-job.yml + parameters: + name: Kitchensink + testScript: tasks/e2e-kitchensink.sh + + # ****************************************************************************** + # Kitchensink Eject test suite + # ****************************************************************************** + - template: azure-pipelines-test-job.yml + parameters: + name: KitchensinkEject + testScript: tasks/e2e-kitchensink-eject.sh + + # ****************************************************************************** + # Behavior test suite + # ****************************************************************************** + - template: azure-pipelines-test-job.yml + parameters: + name: Behavior + testScript: tasks/e2e-behavior.sh + configurations: + LinuxNode10: { vmImage: 'ubuntu-16.04', nodeVersion: 10.x } + LinuxNode12: { vmImage: 'ubuntu-16.04', nodeVersion: 12.x } + WindowsNode10: { vmImage: 'windows-2019', nodeVersion: 10.x } + WindowsNode12: { vmImage: 'windows-2019', nodeVersion: 12.x } + MacNode10: { vmImage: 'macOS-10.15', nodeVersion: 10.x } + MacNode12: { vmImage: 'macOS-10.15', nodeVersion: 12.x } + + # ****************************************************************************** + # Old Node test suite + # ****************************************************************************** + - job: OldNode + pool: + vmImage: ubuntu-latest + steps: + - task: NodeTool@0 + inputs: + versionSpec: 8.x + displayName: 'Install Node.js 8.x' + - bash: tasks/e2e-old-node.sh + displayName: 'Run tests' diff --git a/docusaurus/docs/adding-custom-environment-variables.md b/docusaurus/docs/adding-custom-environment-variables.md index b604a10c810..48bfea2cf64 100644 --- a/docusaurus/docs/adding-custom-environment-variables.md +++ b/docusaurus/docs/adding-custom-environment-variables.md @@ -132,8 +132,8 @@ REACT_APP_NOT_SECRET_CODE=abcdef 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 start`: `.env.development.local`, `.env.local`, `.env.development`, `.env` +- `npm run build`: `.env.production.local`, `.env.local`, `.env.production`, `.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. diff --git a/docusaurus/docs/adding-typescript.md b/docusaurus/docs/adding-typescript.md index 40c9c2242a8..6f4c86c6cc7 100644 --- a/docusaurus/docs/adding-typescript.md +++ b/docusaurus/docs/adding-typescript.md @@ -19,11 +19,11 @@ npx create-react-app my-app --template typescript yarn create react-app my-app --template typescript ``` -> If you've previously installed `create-react-app` globally via `npm install -g create-react-app`, we recommend you uninstall the package using `npm uninstall -g create-react-app` to ensure that `npx` always uses the latest version. +> If you've previously installed `create-react-app` globally via `npm install -g create-react-app`, we recommend you uninstall the package using `npm uninstall -g create-react-app` or `yarn global remove create-react-app` to ensure that `npx` always uses the latest version. > > Global installs of `create-react-app` are no longer supported. -To add [TypeScript](https://www.typescriptlang.org/) to a Create React App project, first install it: +To add [TypeScript](https://www.typescriptlang.org/) to an existing Create React App project, first install it: ```sh npm install --save typescript @types/node @types/react @types/react-dom @types/jest @@ -47,7 +47,7 @@ You are not required to make a [`tsconfig.json` file](https://www.typescriptlang ## Troubleshooting -If your project is not created with TypeScript enabled, npx may be using a cached version of `create-react-app`. Remove previously installed versions with `npm uninstall -g create-react-app` (see [#6119](https://github.com/facebook/create-react-app/issues/6119#issuecomment-451614035)). +If your project is not created with TypeScript enabled, npx may be using a cached version of `create-react-app`. Remove previously installed versions with `npm uninstall -g create-react-app` or `yarn global remove create-react-app` (see [#6119](https://github.com/facebook/create-react-app/issues/6119#issuecomment-451614035)). If you are currently using [create-react-app-typescript](https://github.com/wmonk/create-react-app-typescript/), see [this blog post](https://vincenttunru.com/migrate-create-react-app-typescript-to-create-react-app/) for instructions on how to migrate to Create React App. diff --git a/docusaurus/docs/advanced-configuration.md b/docusaurus/docs/advanced-configuration.md index fb71df0e231..6da2ad174e0 100644 --- a/docusaurus/docs/advanced-configuration.md +++ b/docusaurus/docs/advanced-configuration.md @@ -22,9 +22,7 @@ You can adjust various development and production settings by setting environmen | REACT_EDITOR | ✅ Used | 🚫 Ignored | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebook/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH]() environment variable points to your editor’s bin folder. You can also set it to `none` to disable it completely. | | CHOKIDAR_USEPOLLING | ✅ Used | 🚫 Ignored | 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 | 🚫 Ignored | ✅ Used | When set to `false`, source maps are not generated for a production build. This solves out of memory (OOM) issues on some smaller machines. | -| NODE_PATH | ✅ Used | ✅ Used | 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`. | | INLINE_RUNTIME_CHUNK | 🚫 Ignored | ✅ Used | By default, Create React App will embed the runtime script into `index.html` during the production build. When set to `false`, the script will not be embedded and will be imported as usual. This is normally required when dealing with CSP. | | IMAGE_INLINE_SIZE_LIMIT | 🚫 Ignored | ✅ Used | By default, images smaller than 10,000 bytes are encoded as a data URI in base64 and inlined in the CSS or JS build artifact. Set this to control the size limit in bytes. Setting it to 0 will disable the inlining of images. | -| EXTEND_ESLINT | ✅ Used | ✅ Used | When set to `true`, user provided ESLint configs will be used by `eslint-loader`. Note that any rules set to `"error"` will stop the application from building. | -| FAST_REFRESH | ✅ Used | 🚫 Ignored | When set to `true`, enables experimental support for fast refresh to allow you to tweak your components in real time without reloading the page. | +| FAST_REFRESH | ✅ Used | 🚫 Ignored | When set to `false`, disables experimental support for Fast Refresh to allow you to tweak your components in real time without reloading the page. | | TSC_COMPILE_ON_ERROR | ✅ Used | ✅ Used | When set to `true`, you can run and properly build TypeScript projects even if there are TypeScript type check errors. These errors are printed as warnings in the terminal and/or browser console. | diff --git a/docusaurus/docs/deployment.md b/docusaurus/docs/deployment.md index dfb2e13d6aa..201ce21cd76 100644 --- a/docusaurus/docs/deployment.md +++ b/docusaurus/docs/deployment.md @@ -1,497 +1,508 @@ ---- -id: deployment -title: Deployment -sidebar_label: Deployment ---- - -`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..js` are served with the contents of the `/static/js/main..js` file. For more information see the [production build](production-build.md) section. - -## Static Server - -For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest: - -```sh -npm install -g serve -serve -s build -``` - -The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-l` or `--listen` flags: - -```sh -serve -s build -l 4000 -``` - -Run this command to get a full list of the options available: - -```sh -serve -h -``` - -## Other Solutions - -You don’t necessarily need a static server in order to run a Create React App project in production. It also works well when integrated into an existing server side app. - -Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](https://expressjs.com/): - -```javascript -const express = require('express'); -const path = require('path'); -const app = express(); - -app.use(express.static(path.join(__dirname, 'build'))); - -app.get('/', function(req, res) { - res.sendFile(path.join(__dirname, 'build', 'index.html')); -}); - -app.listen(9000); -``` - -The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node. - -The `build` folder with static assets is the only output produced by Create React App. - -However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like `/todos/42` in your single-page app. - -## Serving Apps with Client-Side Routing - -If you use routers that use the HTML5 [`pushState` history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) under the hood (for example, [React Router](https://github.com/ReactTraining/react-router) with `browserHistory`), many static file servers will fail. For example, if you used React Router with a route for `/todos/42`, the development server will respond to `localhost:3000/todos/42` properly, but an Express serving a production build as above will not. - -This is because when there is a fresh page load for a `/todos/42`, the server looks for the file `build/todos/42` and does not find it. The server needs to be configured to respond to a request to `/todos/42` by serving `index.html`. For example, we can amend our Express example above to serve `index.html` for any unknown paths: - -```diff - app.use(express.static(path.join(__dirname, 'build'))); - --app.get('/', function (req, res) { -+app.get('/*', function (req, res) { - res.sendFile(path.join(__dirname, 'build', 'index.html')); - }); -``` - -If you’re using [Apache HTTP Server](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this: - -``` - Options -MultiViews - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteRule ^ index.html [QSA,L] -``` - -It will get copied to the `build` folder when you run `npm run build`. - -If you’re using [Apache Tomcat](https://tomcat.apache.org/), you need to follow [this Stack Overflow answer](https://stackoverflow.com/a/41249464/4878474). - -Now requests to `/todos/42` will be handled correctly both in development and in production. - -On a production build, and when you've [opted-in](making-a-progressive-web-app.md#why-opt-in), -a [service worker](https://developers.google.com/web/fundamentals/primers/service-workers/) will automatically handle all navigation requests, like for -`/todos/42`, by serving the cached copy of your `index.html`. This -service worker navigation routing can be configured or disabled by -[`eject`ing](available-scripts.md#npm-run-eject) and then modifying the -[`navigateFallback`](https://github.com/GoogleChrome/sw-precache#navigatefallback-string) -and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp) -options of the `SWPrecachePlugin` [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. - -To override this, specify the `homepage` in your `package.json`, for example: - -```js - "homepage": "http://mywebsite.com/relativepath", -``` - -This will let Create React App correctly infer the root path to use in the generated HTML file. - -**Note**: If you are using `react-router@^4`, you can root ``s using the `basename` prop on any ``. - -More information [here](https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string). - -For example: - -```js - - // renders -``` - -### Serving the Same Build from Different Paths - -> Note: this feature is available with `react-scripts@0.9.0` and higher. - -If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`: - -```js - "homepage": ".", -``` - -This will make sure that all the asset paths are relative to `index.html`. You will then be able to move your app from `http://mywebsite.com` to `http://mywebsite.com/relativepath` or even `http://mywebsite.com/relative/path` without having to rebuild it. - -## Customizing Environment Variables for Arbitrary Build Environments - -You can create an arbitrary build environment by creating a custom `.env` file and loading it using [env-cmd](https://www.npmjs.com/package/env-cmd). - -For example, to create a build environment for a staging environment: - -1. Create a file called `.env.staging` -1. Set environment variables as you would any other `.env` file (e.g. `REACT_APP_API_URL=http://api-staging.example.com`) -1. Install [env-cmd](https://www.npmjs.com/package/env-cmd) - ```sh - $ npm install env-cmd --save - $ # or - $ yarn add env-cmd - ``` -1. Add a new script to your `package.json`, building with your new environment: - ```json - { - "scripts": { - "build:staging": "env-cmd -f .env.staging npm run build" - } - } - ``` - -Now you can run `npm run build:staging` to build with the staging environment config. -You can specify other environments in the same way. - -Variables in `.env.production` will be used as fallback because `NODE_ENV` will always be set to `production` for a build. - -## [AWS Amplify](http://console.amplify.aws) - -The AWS Amplify Console provides continuous deployment and hosting for modern web apps (single page apps and static site generators) with serverless backends. The Amplify Console offers globally available CDNs, custom domain setup, feature branch deployments, and password protection. - -1. Login to the Amplify Console [here](https://console.aws.amazon.com/amplify/home). -1. Connect your Create React App repo and pick a branch. If you're looking for a Create React App+Amplify starter, try the [create-react-app-auth-amplify starter](https://github.com/swaminator/create-react-app-auth-amplify) that demonstrates setting up auth in 10 minutes with Create React App. -1. The Amplify Console automatically detects the build settings. Choose Next. -1. Choose _Save and deploy_. - -If the build succeeds, the app is deployed and hosted on a global CDN with an amplifyapp.com domain. You can now continuously deploy changes to your frontend or backend. Continuous deployment allows developers to deploy updates to their frontend and backend on every code commit to their Git repository. - -## [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. - -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. - -Then run the `firebase init` command from your project’s root. You need to choose the **Hosting: Configure and deploy Firebase Hosting sites** and choose the Firebase project you created in the previous step. You will need to agree with `database.rules.json` being created, choose `build` as the public directory, and also agree to **Configure as a single-page app** by replying with `y`. - -```sh - === Project Setup - - First, let's associate this project directory with a Firebase project. - You can create multiple project aliases by running firebase use --add, - but for now we'll set up a default project. - - ? What Firebase project do you want to associate as default? Example app (example-app-fd690) - - === Database Setup - - Firebase Realtime Database Rules allow you to define how your data should be - structured and when your data can be read from and written to. - - ? What file should be used for Database Rules? database.rules.json - ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json. - Future modifications to database.rules.json will update Database Rules when you run - firebase deploy. - - === Hosting Setup - - Your public directory is the folder (relative to your project directory) that - will contain Hosting assets to uploaded with firebase deploy. If you - have a build process for your assets, use your build's output directory. - - ? What do you want to use as your public directory? build - ? Configure as a single-page app (rewrite all urls to /index.html)? Yes - ✔ Wrote build/index.html - - i Writing configuration info to firebase.json... - i Writing project information to .firebaserc... - - ✔ Firebase initialization complete! -``` - -IMPORTANT: you need to set proper HTTP caching headers for `service-worker.js` file in `firebase.json` file or you will not be able to see changes after first deployment ([issue #2440](https://github.com/facebook/create-react-app/issues/2440)). It should be added inside `"hosting"` key like next: - -```json -{ - "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 - === Deploying to 'example-app-fd690'... - - i deploying database, hosting - ✔ database: rules ready to deploy. - i hosting: preparing build directory for upload... - Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully - ✔ hosting: 8 files uploaded successfully - i starting release process (may take several minutes)... - - ✔ Deploy complete! - - Project Console: https://console.firebase.google.com/project/example-app-fd690/overview - Hosting URL: https://example-app-fd690.firebaseapp.com -``` - -For more information see [Firebase Hosting](https://firebase.google.com/docs/hosting). - -## [GitHub Pages](https://pages.github.com/) - -> Note: this feature is available with `react-scripts@0.2.0` and higher. - -### Step 1: Add `homepage` to `package.json` - -**The step below is important!**
- -**If you skip it, your app will not deploy correctly.** - -Open your `package.json` and add a `homepage` field for your project: - -```json - "homepage": "https://myusername.github.io/my-app", -``` - -or for a GitHub user page: - -```json - "homepage": "https://myusername.github.io", -``` - -or for a custom domain page: - -```json - "homepage": "https://mywebsite.com", -``` - -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` - -Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages. - -To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run: - -```sh -npm install --save gh-pages -``` - -Alternatively you may use `yarn`: - -```sh -yarn add gh-pages -``` - -Add the following scripts in your `package.json`: - -```diff - "scripts": { -+ "predeploy": "npm run build", -+ "deploy": "gh-pages -d build", - "start": "react-scripts start", - "build": "react-scripts build", -``` - -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 one -additional modification: - -1. 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: - -```sh -npm run deploy -``` - -### Step 4: For a project page, ensure your project’s settings use `gh-pages` - -Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch: - -gh-pages branch setting - -### Step 5: Optionally, configure the domain - -You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder. - -Your CNAME file should look like this: - -``` -mywebsite.com -``` - -### Notes on client-side routing - -GitHub Pages doesn’t support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions: - -- 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 404s by redirecting to your `index.html` page with a custom 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). - -### 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 following: - -1. Create a new [Personal Access Token](https://github.com/settings/tokens) -2. `git remote set-url origin https://:@github.com//` . -3. Try `npm run deploy` again - -#### "Cannot read property 'email' of null" - -If, when deploying, you get `Cannot read property 'email' of null`, try the following: - -1. `git config --global user.name ''` -2. `git config --global user.email ''` -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). - -You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration). - -### Resolving Heroku Deployment Errors - -Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases. - -#### "Module not found: Error: Cannot resolve 'file' or 'directory'" - -If you get something like this: - -``` -remote: Failed to create a production build. Reason: -remote: Module not found: Error: Cannot resolve 'file' or 'directory' -MyDirectory in /tmp/build_1234/src -``` - -It means you need to ensure that the lettercase of the file or directory you `import` matches the one you see on your filesystem or on GitHub. - -This is important because Linux (the operating system used by Heroku) is case sensitive. So `MyDirectory` and `mydirectory` are two distinct directories and thus, even though the project builds locally, the difference in case breaks the `import` statements on Heroku remotes. - -#### "Could not find a required file." - -If you exclude or ignore necessary files from the package you will see a error similar this one: - -``` -remote: Could not find a required file. -remote: Name: `index.html` -remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public -remote: -remote: npm ERR! Linux 3.13.0-105-generic -remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build" -``` - -In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local `.gitignore` or `~/.gitignore_global`. - -## [Netlify](https://www.netlify.com/) - -**To do a manual deploy to Netlify’s CDN:** - -```sh -npm install netlify-cli -g -netlify deploy -``` - -Choose `build` as the path to deploy. - -**To setup continuous delivery:** - -With this setup Netlify will build and deploy when you push to git or open a pull request: - -1. [Start a new netlify project](https://app.netlify.com/signup) -2. Pick your Git hosting service and select your repository -3. Click `Build your site` - -**Support for client-side routing:** - -To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules: - -``` -/* /index.html 200 -``` - -When you build the project, Create React App will place the `public` folder contents into the build output. - -## [ZEIT Now](https://zeit.co) - -[ZEIT Now](https://zeit.co) is a cloud platform for websites and serverless APIs, that you can use to deploy your Create React App projects to your personal domain (or a free `.now.sh` suffixed URL). - -This guide will show you how to get started in a few quick steps: - -### Step 1: Installing Now CLI - -To install their command-line interface with [npm](https://www.npmjs.com/package/now), run the following command: - -```shell -npm i -g now -``` - -### Step 2: Deploying - -You can deploy your application by running the following command in the root of the project directory: - -```shell -now -``` - -**Alternatively**, you can also use their integration for [GitHub](https://zeit.co/github) or [GitLab](https://zeit.co/gitlab). - -That’s all! - -Your site will now deploy, and you will receive a link similar to the following: https://react.now-examples.now.sh - -Out of the box, you are preconfigured for client-side routing compatibility and appropriate default caching headers. This behaviour can be overwritten [like this](https://zeit.co/docs/v2/advanced/routes/). - -## [Render](https://render.com) - -Render offers free [static site](https://render.com/docs/static-sites) hosting with fully managed SSL, a global CDN and continuous auto deploys from GitHub. - -Deploy your app in only a few minutes by following the [Create React App deployment guide](https://render.com/docs/deploy-create-react-app). - -Use invite code `cra` to sign up or use [this link](https://render.com/i/cra). - -## [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. If you are looking to add a custom domain, HTTPS and continuous deployment see this [blog post](https://medium.com/dailyjs/a-guide-to-deploying-your-react-app-with-aws-s3-including-https-a-custom-domain-a-cdn-and-58245251f081). - -## [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. - -When asked about the project path, make sure to specify the `build` folder, for example: - -```sh - project path: /path/to/project/build -``` - -Note that in order to support routers that use HTML5 `pushState` API, you may want to rename the `index.html` in your build folder to `200.html` before deploying to Surge. This [ensures that every URL falls back to that file](https://surge.sh/help/adding-a-200-page-for-client-side-routing). - -## 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. +--- +id: deployment +title: Deployment +sidebar_label: Deployment +--- + +`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..js` are served with the contents of the `/static/js/main..js` file. For more information see the [production build](production-build.md) section. + +## Static Server + +For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest: + +```sh +npm install -g serve +serve -s build +``` + +The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-l` or `--listen` flags: + +```sh +serve -s build -l 4000 +``` + +Run this command to get a full list of the options available: + +```sh +serve -h +``` + +## Other Solutions + +You don’t necessarily need a static server in order to run a Create React App project in production. It also works well when integrated into an existing server side app. + +Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](https://expressjs.com/): + +```javascript +const express = require('express'); +const path = require('path'); +const app = express(); + +app.use(express.static(path.join(__dirname, 'build'))); + +app.get('/', function (req, res) { + res.sendFile(path.join(__dirname, 'build', 'index.html')); +}); + +app.listen(9000); +``` + +The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node. + +The `build` folder with static assets is the only output produced by Create React App. + +However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like `/todos/42` in your single-page app. + +## Serving Apps with Client-Side Routing + +If you use routers that use the HTML5 [`pushState` history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) under the hood (for example, [React Router](https://github.com/ReactTraining/react-router) with `browserHistory`), many static file servers will fail. For example, if you used React Router with a route for `/todos/42`, the development server will respond to `localhost:3000/todos/42` properly, but an Express serving a production build as above will not. + +This is because when there is a fresh page load for a `/todos/42`, the server looks for the file `build/todos/42` and does not find it. The server needs to be configured to respond to a request to `/todos/42` by serving `index.html`. For example, we can amend our Express example above to serve `index.html` for any unknown paths: + +```diff + app.use(express.static(path.join(__dirname, 'build'))); + +-app.get('/', function (req, res) { ++app.get('/*', function (req, res) { + res.sendFile(path.join(__dirname, 'build', 'index.html')); + }); +``` + +If you’re using [Apache HTTP Server](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this: + +``` + Options -MultiViews + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^ index.html [QSA,L] +``` + +It will get copied to the `build` folder when you run `npm run build`. + +If you’re using [Apache Tomcat](https://tomcat.apache.org/), you need to follow [this Stack Overflow answer](https://stackoverflow.com/a/41249464/4878474). + +Now requests to `/todos/42` will be handled correctly both in development and in production. + +On a production build, and when you've [opted-in](making-a-progressive-web-app.md#why-opt-in), +a [service worker](https://developers.google.com/web/fundamentals/primers/service-workers/) will automatically handle all navigation requests, like for +`/todos/42`, by serving the cached copy of your `index.html`. This +service worker navigation routing can be configured or disabled by +[`eject`ing](available-scripts.md#npm-run-eject) and then modifying the +[`navigateFallback`](https://github.com/GoogleChrome/sw-precache#navigatefallback-string) +and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp) +options of the `SWPrecachePlugin` configuration. + +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` 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. + +To override this, specify the `homepage` in your `package.json`, for example: + +```js + "homepage": "http://mywebsite.com/relativepath", +``` + +This will let Create React App correctly infer the root path to use in the generated HTML file. + +**Note**: If you are using `react-router@^4`, you can root ``s using the `basename` prop on any ``. + +More information [here](https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string). + +For example: + +```js + + // renders
+``` + +### Serving the Same Build from Different Paths + +> Note: this feature is available with `react-scripts@0.9.0` and higher. + +If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`: + +```js + "homepage": ".", +``` + +This will make sure that all the asset paths are relative to `index.html`. You will then be able to move your app from `http://mywebsite.com` to `http://mywebsite.com/relativepath` or even `http://mywebsite.com/relative/path` without having to rebuild it. + +## Customizing Environment Variables for Arbitrary Build Environments + +You can create an arbitrary build environment by creating a custom `.env` file and loading it using [env-cmd](https://www.npmjs.com/package/env-cmd). + +For example, to create a build environment for a staging environment: + +1. Create a file called `.env.staging` +1. Set environment variables as you would any other `.env` file (e.g. `REACT_APP_API_URL=http://api-staging.example.com`) +1. Install [env-cmd](https://www.npmjs.com/package/env-cmd) + ```sh + $ npm install env-cmd --save + $ # or + $ yarn add env-cmd + ``` +1. Add a new script to your `package.json`, building with your new environment: + ```json + { + "scripts": { + "build:staging": "env-cmd -f .env.staging npm run build" + } + } + ``` + +Now you can run `npm run build:staging` to build with the staging environment config. +You can specify other environments in the same way. + +Variables in `.env.production` will be used as fallback because `NODE_ENV` will always be set to `production` for a build. + +## [AWS Amplify](http://console.amplify.aws) + +The AWS Amplify Console provides continuous deployment and hosting for modern web apps (single page apps and static site generators) with serverless backends. The Amplify Console offers globally available CDNs, custom domain setup, feature branch deployments, and password protection. + +1. Login to the Amplify Console [here](https://console.aws.amazon.com/amplify/home). +1. Connect your Create React App repo and pick a branch. If you're looking for a Create React App+Amplify starter, try the [create-react-app-auth-amplify starter](https://github.com/swaminator/create-react-app-auth-amplify) that demonstrates setting up auth in 10 minutes with Create React App. +1. The Amplify Console automatically detects the build settings. Choose Next. +1. Choose _Save and deploy_. + +If the build succeeds, the app is deployed and hosted on a global CDN with an amplifyapp.com domain. You can now continuously deploy changes to your frontend or backend. Continuous deployment allows developers to deploy updates to their frontend and backend on every code commit to their Git repository. + +## [Azure](https://azure.microsoft.com/) + +Azure Static Web Apps creates an automated build and deploy pipeline for your React app powered by GitHub Actions. Applications are geo-distributed by default with multiple points of presence. PR's are built automatically for staging environment previews. + +1. Create a new Static Web App [here](https://ms.portal.azure.com/#create/Microsoft.StaticApp). +1. Add in the details and connect to your GitHub repo. +1. Make sure the build folder is set correctly on the "build" tab and create the resource. + +Azure Static Web Apps will automatically configure a GitHub Action in your repo and begin the deployment. + +See the [Azure Static Web Apps documentation](https://aka.ms/swadocs) for more information on routing, APIs, authentication and authorization, custom domains and more. + +## [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. + +Then run the `firebase init` command from your project’s root. You need to choose the **Hosting: Configure and deploy Firebase Hosting sites** and choose the Firebase project you created in the previous step. You will need to agree with `database.rules.json` being created, choose `build` as the public directory, and also agree to **Configure as a single-page app** by replying with `y`. + +```sh + === Project Setup + + First, let's associate this project directory with a Firebase project. + You can create multiple project aliases by running firebase use --add, + but for now we'll set up a default project. + + ? What Firebase project do you want to associate as default? Example app (example-app-fd690) + + === Database Setup + + Firebase Realtime Database Rules allow you to define how your data should be + structured and when your data can be read from and written to. + + ? What file should be used for Database Rules? database.rules.json + ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json. + Future modifications to database.rules.json will update Database Rules when you run + firebase deploy. + + === Hosting Setup + + Your public directory is the folder (relative to your project directory) that + will contain Hosting assets to uploaded with firebase deploy. If you + have a build process for your assets, use your build's output directory. + + ? What do you want to use as your public directory? build + ? Configure as a single-page app (rewrite all urls to /index.html)? Yes + ✔ Wrote build/index.html + + i Writing configuration info to firebase.json... + i Writing project information to .firebaserc... + + ✔ Firebase initialization complete! +``` + +IMPORTANT: you need to set proper HTTP caching headers for `service-worker.js` file in `firebase.json` file or you will not be able to see changes after first deployment ([issue #2440](https://github.com/facebook/create-react-app/issues/2440)). It should be added inside `"hosting"` key like next: + +```json +{ + "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 + === Deploying to 'example-app-fd690'... + + i deploying database, hosting + ✔ database: rules ready to deploy. + i hosting: preparing build directory for upload... + Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully + ✔ hosting: 8 files uploaded successfully + i starting release process (may take several minutes)... + + ✔ Deploy complete! + + Project Console: https://console.firebase.google.com/project/example-app-fd690/overview + Hosting URL: https://example-app-fd690.firebaseapp.com +``` + +For more information see [Firebase Hosting](https://firebase.google.com/docs/hosting). + +## [GitHub Pages](https://pages.github.com/) + +> Note: this feature is available with `react-scripts@0.2.0` and higher. + +### Step 1: Add `homepage` to `package.json` + +**The step below is important!**
+ +**If you skip it, your app will not deploy correctly.** + +Open your `package.json` and add a `homepage` field for your project: + +```json + "homepage": "https://myusername.github.io/my-app", +``` + +or for a GitHub user page: + +```json + "homepage": "https://myusername.github.io", +``` + +or for a custom domain page: + +```json + "homepage": "https://mywebsite.com", +``` + +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` + +Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages. + +To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run: + +```sh +npm install --save gh-pages +``` + +Alternatively you may use `yarn`: + +```sh +yarn add gh-pages +``` + +Add the following scripts in your `package.json`: + +```diff + "scripts": { ++ "predeploy": "npm run build", ++ "deploy": "gh-pages -d build", + "start": "react-scripts start", + "build": "react-scripts build", +``` + +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 one +additional modification: + +1. 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: + +```sh +npm run deploy +``` + +### Step 4: For a project page, ensure your project’s settings use `gh-pages` + +Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch: + +gh-pages branch setting + +### Step 5: Optionally, configure the domain + +You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder. + +Your CNAME file should look like this: + +``` +mywebsite.com +``` + +### Notes on client-side routing + +GitHub Pages doesn’t support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions: + +- 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 404s by redirecting to your `index.html` page with a custom 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). + +### 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 following: + +1. Create a new [Personal Access Token](https://github.com/settings/tokens) +2. `git remote set-url origin https://:@github.com//` . +3. Try `npm run deploy` again + +#### "Cannot read property 'email' of null" + +If, when deploying, you get `Cannot read property 'email' of null`, try the following: + +1. `git config --global user.name ''` +2. `git config --global user.email ''` +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). + +You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration). + +### Resolving Heroku Deployment Errors + +Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases. + +#### "Module not found: Error: Cannot resolve 'file' or 'directory'" + +If you get something like this: + +``` +remote: Failed to create a production build. Reason: +remote: Module not found: Error: Cannot resolve 'file' or 'directory' +MyDirectory in /tmp/build_1234/src +``` + +It means you need to ensure that the lettercase of the file or directory you `import` matches the one you see on your filesystem or on GitHub. + +This is important because Linux (the operating system used by Heroku) is case sensitive. So `MyDirectory` and `mydirectory` are two distinct directories and thus, even though the project builds locally, the difference in case breaks the `import` statements on Heroku remotes. + +#### "Could not find a required file." + +If you exclude or ignore necessary files from the package you will see a error similar this one: + +``` +remote: Could not find a required file. +remote: Name: `index.html` +remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public +remote: +remote: npm ERR! Linux 3.13.0-105-generic +remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build" +``` + +In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local `.gitignore` or `~/.gitignore_global`. + +## [Netlify](https://www.netlify.com/) + +**To do a manual deploy to Netlify’s CDN:** + +```sh +npm install netlify-cli -g +netlify deploy +``` + +Choose `build` as the path to deploy. + +**To setup continuous delivery:** + +With this setup Netlify will build and deploy when you push to git or open a pull request: + +1. [Start a new netlify project](https://app.netlify.com/signup) +2. Pick your Git hosting service and select your repository +3. Click `Build your site` + +**Support for client-side routing:** + +To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules: + +``` +/* /index.html 200 +``` + +When you build the project, Create React App will place the `public` folder contents into the build output. + +## [Vercel](https://vercel.com) + +[Vercel](https://vercel.com/home) is a cloud platform that enables developers to host Jamstack websites and web services that deploy instantly, scale automatically, and requires no supervision, all with zero configuration. They provide a global edge network, SSL encryption, asset compression, cache invalidation, and more. + +### Step 1: Deploying your React project to Vercel + +To deploy your React project with a [Vercel for Git Integration](https://vercel.com/docs/git-integrations), make sure it has been pushed to a Git repository. + +Import the project into Vercel using the [Import Flow](https://vercel.com/import/git). During the import, you will find all relevant [options](https://vercel.com/docs/build-step#build-&-development-settings) preconfigured for you with the ability to change as needed. + +After your project has been imported, all subsequent pushes to branches will generate [Preview Deployments](https://vercel.com/docs/platform/deployments#preview), and all changes made to the [Production Branch](https://vercel.com/docs/git-integrations#production-branch) (commonly "master" or "main") will result in a [Production Deployment](https://vercel.com/docs/platform/deployments#production). + +Once deployed, you will get a URL to see your app live, such as the following: https://create-react-app-example.vercel.app/. + +### Step 2 (optional): Using a Custom Domain + +If you want to use a Custom Domain with your Vercel deployment, you can **Add** or **Transfer in** your domain via your Vercel [account Domain settings.](https://vercel.com/dashboard/domains) + +To add your domain to your project, navigate to your [Project](https://vercel.com/docs/platform/projects) from the Vercel Dashboard. Once you have selected your project, click on the "Settings" tab, then select the **Domains** menu item. From your projects **Domain** page, enter the domain you wish to add to your project. + +Once the domain as been added, you will be presented with different methods for configuring it. + +### Deploying a fresh React project + +You can deploy a fresh React project, with a Git repository set up for you, with the following Deploy Button: + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/git?s=https%3A%2F%2Fgithub.com%2Fvercel%2Fvercel%2Ftree%2Fmaster%2Fexamples%2Fcreate-react-app) + +### Vercel References: + +- [Example Source](https://github.com/vercel/vercel/tree/master/examples/create-react-app) +- [Official Vercel Guide](https://vercel.com/guides/deploying-react-with-vercel-cra) +- [Vercel Deployment Docs](https://vercel.com/docs) +- [Vercel Custom Domain Docs](https://vercel.com/docs/custom-domains) + +## [Render](https://render.com) + +Render offers free [static site](https://render.com/docs/static-sites) hosting with fully managed SSL, a global CDN and continuous auto deploys from GitHub. + +Deploy your app in only a few minutes by following the [Create React App deployment guide](https://render.com/docs/deploy-create-react-app). + +Use invite code `cra` to sign up or use [this link](https://render.com/i/cra). + +## [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. If you are looking to add a custom domain, HTTPS and continuous deployment see this [blog post](https://medium.com/dailyjs/a-guide-to-deploying-your-react-app-with-aws-s3-including-https-a-custom-domain-a-cdn-and-58245251f081). + +## [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. + +When asked about the project path, make sure to specify the `build` folder, for example: + +```sh + project path: /path/to/project/build +``` + +Note that in order to support routers that use HTML5 `pushState` API, you may want to rename the `index.html` in your build folder to `200.html` before deploying to Surge. This [ensures that every URL falls back to that file](https://surge.sh/help/adding-a-200-page-for-client-side-routing). + +## 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. diff --git a/docusaurus/docs/getting-started.md b/docusaurus/docs/getting-started.md index 9418ca03c07..b95bc100470 100644 --- a/docusaurus/docs/getting-started.md +++ b/docusaurus/docs/getting-started.md @@ -14,7 +14,7 @@ cd my-app npm start ``` -> If you've previously installed `create-react-app` globally via `npm install -g create-react-app`, we recommend you uninstall the package using `npm uninstall -g create-react-app` to ensure that `npx` always uses the latest version. +> If you've previously installed `create-react-app` globally via `npm install -g create-react-app`, we recommend you uninstall the package using `npm uninstall -g create-react-app` or `yarn global remove create-react-app` to ensure that `npx` always uses the latest version. _([npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) comes with npm 5.2+ and higher, see [instructions for older npm versions](https://gist.github.com/gaearon/4064d3c23a77c74a3614c498a8bb1c5f))_ @@ -120,7 +120,8 @@ my-app ├── index.css ├── index.js ├── logo.svg - └── serviceWorker.js + ├── serviceWorker.js + └── setupTests.js ``` No configuration or complicated folder structures, only the files you need to build your app. Once the installation is done, you can open your project folder: diff --git a/docusaurus/docs/making-a-progressive-web-app.md b/docusaurus/docs/making-a-progressive-web-app.md index ba9802e6088..649fb9cb320 100644 --- a/docusaurus/docs/making-a-progressive-web-app.md +++ b/docusaurus/docs/making-a-progressive-web-app.md @@ -5,12 +5,42 @@ title: Making a Progressive Web App The production build has all the tools necessary to generate a first-class [Progressive Web App](https://developers.google.com/web/progressive-web-apps/), -but **the offline/cache-first behavior is opt-in only**. By default, -the build process will generate a service worker file, but it will not be -registered, so it will not take control of your production web app. +but **the offline/cache-first behavior is opt-in only**. + +Starting with Create React App 4, you can add a `src/service-worker.js` file to +your project to use the built-in support for +[Workbox](https://developers.google.com/web/tools/workbox/)'s +[`InjectManifest`](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-webpack-plugin.InjectManifest) +plugin, which will +[compile](https://developers.google.com/web/tools/workbox/guides/using-bundlers) +your service worker and inject into it a list of URLs to +[precache](https://developers.google.com/web/tools/workbox/guides/precache-files). + +If you start a new project using one of the PWA [custom +templates](https://create-react-app.dev/docs/custom-templates/), you'll get a +`src/service-worker.js` file that serves as a good starting point for an +offline-first service worker: + +```sh +npx create-react-app my-app --template cra-template-pwa +``` + +The TypeScript equivalent is: + +```sh +npx create-react-app my-app --template cra-template-pwa-typescript +``` + +If you know that you won't be using service workers, or if you'd prefer to use a +different approach to creating your service worker, don't create a +`src/service-worker.js` file. The `InjectManifest` plugin won't be run in that +case. -In order to opt-in to the offline-first behavior, developers should look for the -following in their [`src/index.js`](https://github.com/facebook/create-react-app/blob/master/packages/cra-template/template/src/index.js) file: +In addition to creating your local `src/service-worker.js` file, it needs to be +registered before it will be used. In order to opt-in to the offline-first +behavior, developers should look for the following in their +[`src/index.js`](https://github.com/facebook/create-react-app/blob/master/packages/cra-template/template/src/index.js) +file: ```js // If you want your app to work offline and load faster, you can change @@ -24,23 +54,59 @@ As the comment states, switching `serviceWorker.unregister()` to ## Why Opt-in? -Offline-first Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience: +Offline-first Progressive Web Apps are faster and more reliable than traditional +web pages, and provide an engaging mobile experience: + +- All static site assets that are a part of your `webpack` build 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. This eliminates the need for the app store. + +However, they [can make debugging deployments more +challenging](https://github.com/facebook/create-react-app/issues/2398). + +The +[`workbox-webpack-plugin`](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin) +is integrated into production configuration, and it will take care of compiling +a service worker file that will automatically precache all of your +`webpack`-generated assets and keep them up to date as you deploy updates. The +service worker will use a [cache-first +strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network) +for handling all requests for `webpack`-generated assets, including [navigation +requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests) +for your HTML, ensuring that your web app is consistently fast, even on a slow +or unreliable network. -- 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. This eliminates the need for the app store. +Note: Resources that are not generated by `webpack`, such as static files that are +copied over from your local +[`public/` directory](https://github.com/facebook/create-react-app/blob/master/packages/cra-template/template/public/) +or third-party resources, will not be precached. You can optionally set up Workbox +[routes](https://developers.google.com/web/tools/workbox/guides/route-requests) +to apply the runtime caching strategy of your choice to those resources. + +## Customization + +Starting with Create React App 4, you have full control over customizing the +logic in this service worker, by creating your own `src/service-worker.js` file, +or customizing the one added by the `cra-template-pwa` (or +`cra-template-pwa-typescript`) template. You can use [additional +modules](https://developers.google.com/web/tools/workbox/modules) from the +Workbox project, add in a push notification library, or remove some of the +default caching logic. The one requirement is that you keep `self.__WB_MANIFEST` +somewhere in your file, as the Workbox compilation plugin checks for this value +when generating a manifest of URLs to precache. If you would prefer not to use +precaching, you can assign `self.__WB_MANIFEST` to a variable that will be +ignored, like: -However, they [can make debugging deployments more challenging](https://github.com/facebook/create-react-app/issues/2398) so, starting with Create React App 2, service workers are opt-in. +```js +// eslint-disable-next-line no-restricted-globals +const ignored = self.__WB_MANIFEST; -The [`workbox-webpack-plugin`](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin) -is integrated into production configuration, -and it will take care of generating a service worker file that will automatically -precache all of your local assets and keep them up to date as you deploy updates. -The service worker will use a [cache-first strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network) -for handling all requests for local assets, including -[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests) -for your HTML, ensuring that your web app is consistently fast, even on a slow -or unreliable network. +// Your custom service worker code goes here. +``` ## Offline-First Considerations @@ -88,7 +154,8 @@ following into account: 1. By default, the generated service worker file will not intercept or cache any cross-origin traffic, like HTTP [API requests](integrating-with-an-api-backend.md), - images, or embeds loaded from a different domain. + images, or embeds loaded from a different domain. Starting with Create + React App 4, this can be customized, as explained above. ## Progressive Web App Metadata diff --git a/docusaurus/docs/measuring-performance.md b/docusaurus/docs/measuring-performance.md new file mode 100644 index 00000000000..a41635cbe40 --- /dev/null +++ b/docusaurus/docs/measuring-performance.md @@ -0,0 +1,65 @@ +--- +id: measuring-performance +title: Measuring Performance +--- + +By default, Create React App includes a performance relayer that allows you to measure and analyze +the performance of your application using different metrics. + +To measure any of the supported metrics, you only need to pass a function into the `reportWebVitals` +function in `index.js`: + +```js +reportWebVitals(console.log); +``` + +This function is fired when the final values for any of the metrics have finished calculating on the +page. You can use it to log any of the results to the console or send to a particular endpoint. + +## Web Vitals + +[Web Vitals](https://web.dev/vitals/) are a set of useful metrics that aim to capture the user +experience of a web page. In Create React App, a third-party library is used to measure these +metrics ([web-vitals](https://github.com/GoogleChrome/web-vitals)). + +To understand more about the object returned to the function when a metric value is calculated, +refer to the [documentation](https://github.com/GoogleChrome/web-vitals/#types). The [Browser +Support](https://github.com/GoogleChrome/web-vitals/#browser-support) section also explains which browsers are supported. + +## Sending results to analytics + +With the `reportWebVitals` function, you can send any of results to an analytics endpoint to measure and track real user performance on your site. For example: + +```js +function sendToAnalytics(metric) { + const body = JSON.stringify(metric); + const url = 'https://example.com/analytics'; + + // Use `navigator.sendBeacon()` if available, falling back to `fetch()` + if (navigator.sendBeacon) { + navigator.sendBeacon(url, body); + } else { + fetch(url, { body, method: 'POST', keepalive: true }); + } +} + +reportWebVitals(sendToAnalytics); +``` + +> **Note:** If you use Google Analytics, use the `id` value to make it easier to construct metric distributions manually (to calculate percentiles, etc…). +> +> ```js +> function sendToAnalytics({ id, name, value }) { +> ga('send', 'event', { +> eventCategory: 'Web Vitals', +> eventAction: name, +> eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers +> eventLabel: id, // id unique to current page load +> nonInteraction: true, // avoids affecting bounce rate +> }); +> } +> +> reportWebVitals(sendToAnalytics); +> ``` +> +> Read more about sending results to Google Analytics [here](https://github.com/GoogleChrome/web-vitals#send-the-results-to-google-analytics). diff --git a/docusaurus/docs/running-tests.md b/docusaurus/docs/running-tests.md index a757355e018..ccc3fecd9a1 100644 --- a/docusaurus/docs/running-tests.md +++ b/docusaurus/docs/running-tests.md @@ -85,97 +85,9 @@ This test mounts a component and makes sure that it didn’t throw during render 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. -### Option 1: Shallow Rendering +### React Testing Library -If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](https://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](https://airbnb.io/enzyme/). To install it, run: - -```sh -npm install --save enzyme enzyme-adapter-react-16 react-test-renderer -``` - -Alternatively you may use `yarn`: - -```sh -yarn add enzyme enzyme-adapter-react-16 react-test-renderer -``` - -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'; -import { shallow } from 'enzyme'; -import App from './App'; - -it('renders without crashing', () => { - shallow(); -}); -``` - -Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `