├── .editorconfig ├── .gitignore ├── .rollup.js ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── index.js ├── package.json ├── test-cra1 ├── .gitignore ├── README.md ├── config-overrides.js ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ └── serviceWorker.js └── test-cra2 ├── .gitignore ├── README.md ├── config-overrides.js ├── package.json ├── postcss.config.js ├── public ├── favicon.ico ├── index.html └── manifest.json └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg └── serviceWorker.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_style = tab 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | 10 | [*.md] 11 | trim_trailing_whitespace = false 12 | 13 | [*.{json,md,yml}] 14 | indent_size = 2 15 | indent_style = space 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | index.*.* 3 | package-lock.json 4 | *.log* 5 | .* 6 | !.editorconfig 7 | !.gitignore 8 | !.rollup.js 9 | !.travis.yml 10 | -------------------------------------------------------------------------------- /.rollup.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel'; 2 | 3 | export default { 4 | input: 'index.js', 5 | output: [ 6 | { file: 'index.cjs.js', format: 'cjs', sourcemap: true }, 7 | { file: 'index.es.mjs', format: 'es', sourcemap: true } 8 | ], 9 | plugins: [ 10 | babel({ 11 | presets: [ 12 | ['@babel/env', { modules: false, targets: { node: 8 } }] 13 | ] 14 | }) 15 | ] 16 | }; 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # https://docs.travis-ci.com/user/travis-lint 2 | 3 | language: node_js 4 | 5 | node_js: 6 | - 8 7 | 8 | install: 9 | - npm install --ignore-scripts 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changes to React App Rewire PostCSS 2 | 3 | ### 4.0.0 (May 12, 2019) 4 | 5 | - Updated: Node 8+ compatibility (major) 6 | 7 | ### 3.0.2 (October 13, 2018) 8 | 9 | - Fixed: Issue with loading from postcss.config.js file 10 | 11 | ### 3.0.1 (October 9, 2018) 12 | 13 | - Fixed: Issue with `build` 14 | 15 | ### 3.0.0 (October 3, 2018) 16 | 17 | - Updated: Support for Create React App 2. 18 | - Changed: The old PostCSS plugins are no longer erased, making 19 | configuration-less usage of this plugin seemingly invisible. The plugins are 20 | still replaced the same way. 21 | 22 | ### 2.0.0 (September 17, 2018) 23 | 24 | - Changed: A new configuration is returned, instead of the existing 25 | configuration being mutated. 26 | - Updated: PostCSS Loader v3.0.0 (major) 27 | - Updated: Support for Node v6+ (major) 28 | 29 | ### 1.0.2 (June 5, 2018) 30 | 31 | - Fixed: Issue detecting postcss-loader in Windows 32 | 33 | ### 1.0.1 (June 5, 2018) 34 | 35 | - Improved documentation 36 | - Moved project to csstools 37 | 38 | ### 1.0.0 (June 5, 2018) 39 | 40 | - Initial version 41 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to React App Rewire PostCSS 2 | 3 | You want to help? You rock! Now, take a moment to be sure your contributions 4 | make sense to everyone else. 5 | 6 | ## Reporting Issues 7 | 8 | Found a problem? Want a new feature? 9 | 10 | - See if your issue or idea has [already been reported]. 11 | - Provide a [reduced test case] or a [live example]. 12 | 13 | Remember, a bug is a _demonstrable problem_ caused by _our_ code. 14 | 15 | ## Submitting Pull Requests 16 | 17 | Pull requests are the greatest contributions, so be sure they are focused in 18 | scope and avoid unrelated commits. 19 | 20 | 1. To begin; [fork this project], clone your fork, and add our upstream. 21 | ```bash 22 | # Clone your fork of the repo into the current directory 23 | git clone git@github.com:YOUR_USER/react-app-rewire-postcss.git 24 | 25 | # Navigate to the newly cloned directory 26 | cd react-app-rewire-postcss 27 | 28 | # Assign the original repo to a remote called "upstream" 29 | git remote add upstream git@github.com:csstools/react-app-rewire-postcss.git 30 | 31 | # Install the tools necessary for testing 32 | npm install 33 | ``` 34 | 35 | 2. Create a branch for your feature or fix: 36 | ```bash 37 | # Move into a new branch for your feature 38 | git checkout -b feature/thing 39 | ``` 40 | ```bash 41 | # Move into a new branch for your fix 42 | git checkout -b fix/something 43 | ``` 44 | 45 | 3. If your code follows our practices, then push your feature branch: 46 | ```bash 47 | # Test current code 48 | npm test 49 | ``` 50 | ```bash 51 | # Push the branch for your new feature 52 | git push origin feature/thing 53 | ``` 54 | ```bash 55 | # Or, push the branch for your update 56 | git push origin update/something 57 | ``` 58 | 59 | That’s it! Now [open a pull request] with a clear title and description. 60 | 61 | [already been reported]: issues 62 | [fork this project]: fork 63 | [live example]: https://codepen.io/pen 64 | [open a pull request]: https://help.github.com/articles/using-pull-requests/ 65 | [reduced test case]: https://css-tricks.com/reduced-test-cases/ 66 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # CC0 1.0 Universal 2 | 3 | ## Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an “owner”) of an original work of 8 | authorship and/or a database (each, a “Work”). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific works 12 | (“Commons”) that the public can reliably and without fear of later claims of 13 | infringement build upon, modify, incorporate in other works, reuse and 14 | redistribute as freely as possible in any form whatsoever and for any purposes, 15 | including without limitation commercial purposes. These owners may contribute 16 | to the Commons to promote the ideal of a free culture and the further 17 | production of creative, cultural and scientific works, or to gain reputation or 18 | greater distribution for their Work in part through the use and efforts of 19 | others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation of 22 | additional consideration or compensation, the person associating CC0 with a 23 | Work (the “Affirmer”), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and 25 | publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights (“Copyright and 31 | Related Rights”). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 1. the right to reproduce, adapt, distribute, perform, display, communicate, 34 | and translate a Work; 35 | 2. moral rights retained by the original author(s) and/or performer(s); 36 | 3. publicity and privacy rights pertaining to a person’s image or likeness 37 | depicted in a Work; 38 | 4. rights protecting against unfair competition in regards to a Work, 39 | subject to the limitations in paragraph 4(i), below; 40 | 5. rights protecting the extraction, dissemination, use and reuse of data in 41 | a Work; 42 | 6. database rights (such as those arising under Directive 96/9/EC of the 43 | European Parliament and of the Council of 11 March 1996 on the legal 44 | protection of databases, and under any national implementation thereof, 45 | including any amended or successor version of such directive); and 46 | 7. other similar, equivalent or corresponding rights throughout the world 47 | based on applicable law or treaty, and any national implementations 48 | thereof. 49 | 50 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 51 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 52 | unconditionally waives, abandons, and surrenders all of Affirmer’s Copyright 53 | and Related Rights and associated claims and causes of action, whether now 54 | known or unknown (including existing as well as future claims and causes of 55 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 56 | duration provided by applicable law or treaty (including future time 57 | extensions), (iii) in any current or future medium and for any number of 58 | copies, and (iv) for any purpose whatsoever, including without limitation 59 | commercial, advertising or promotional purposes (the “Waiver”). Affirmer 60 | makes the Waiver for the benefit of each member of the public at large and 61 | to the detriment of Affirmer’s heirs and successors, fully intending that 62 | such Waiver shall not be subject to revocation, rescission, cancellation, 63 | termination, or any other legal or equitable action to disrupt the quiet 64 | enjoyment of the Work by the public as contemplated by Affirmer’s express 65 | Statement of Purpose. 66 | 67 | 3. Public License Fallback. Should any part of the Waiver for any reason be 68 | judged legally invalid or ineffective under applicable law, then the Waiver 69 | shall be preserved to the maximum extent permitted taking into account 70 | Affirmer’s express Statement of Purpose. In addition, to the extent the 71 | Waiver is so judged Affirmer hereby grants to each affected person a 72 | royalty-free, non transferable, non sublicensable, non exclusive, 73 | irrevocable and unconditional license to exercise Affirmer’s Copyright and 74 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 75 | maximum duration provided by applicable law or treaty (including future time 76 | extensions), (iii) in any current or future medium and for any number of 77 | copies, and (iv) for any purpose whatsoever, including without limitation 78 | commercial, advertising or promotional purposes (the “License”). The License 79 | shall be deemed effective as of the date CC0 was applied by Affirmer to the 80 | Work. Should any part of the License for any reason be judged legally 81 | invalid or ineffective under applicable law, such partial invalidity or 82 | ineffectiveness shall not invalidate the remainder of the License, and in 83 | such case Affirmer hereby affirms that he or she will not (i) exercise any 84 | of his or her remaining Copyright and Related Rights in the Work or (ii) 85 | assert any associated claims and causes of action with respect to the Work, 86 | in either case contrary to Affirmer’s express Statement of Purpose. 87 | 88 | 4. Limitations and Disclaimers. 89 | 1. No trademark or patent rights held by Affirmer are waived, abandoned, 90 | surrendered, licensed or otherwise affected by this document. 91 | 2. Affirmer offers the Work as-is and makes no representations or warranties 92 | of any kind concerning the Work, express, implied, statutory or 93 | otherwise, including without limitation warranties of title, 94 | merchantability, fitness for a particular purpose, non infringement, or 95 | the absence of latent or other defects, accuracy, or the present or 96 | absence of errors, whether or not discoverable, all to the greatest 97 | extent permissible under applicable law. 98 | 3. Affirmer disclaims responsibility for clearing rights of other persons 99 | that may apply to the Work or any use thereof, including without 100 | limitation any person’s Copyright and Related Rights in the Work. 101 | Further, Affirmer disclaims responsibility for obtaining any necessary 102 | consents, permissions or other rights required for any use of the Work. 103 | 4. Affirmer understands and acknowledges that Creative Commons is not a 104 | party to this document and has no duty or obligation with respect to this 105 | CC0 or use of the Work. 106 | 107 | For more information, please see 108 | http://creativecommons.org/publicdomain/zero/1.0/. 109 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
⚠️ React App Rewire PostCSS has been deprecated. ⚠️
2 | 3 | # React App Rewire PostCSS [PostCSS Logo][postcss] 4 | 5 | [![NPM Version][npm-img]][npm-url] 6 | [![Build Status][cli-img]][cli-url] 7 | [![Support Chat][git-img]][git-url] 8 | 9 | [React App Rewire PostCSS] lets you configure [PostCSS] in [Create React App] 10 | v1 and v2 without ejecting. 11 | 12 | ## Usage 13 | 14 | Add [React App Rewire PostCSS] to your [Rewired] React app: 15 | 16 | ```bash 17 | npm install react-app-rewire-postcss --save-dev 18 | ``` 19 | 20 | Next, add [React App Rewire PostCSS] to `config-overrides.js` in your React app 21 | directory: 22 | 23 | ```js 24 | module.exports = config => { 25 | require('react-app-rewire-postcss')(config/*, options */); 26 | 27 | return config; 28 | }; 29 | ``` 30 | 31 | That’s it! Now you can control PostCSS with all the configuration options from 32 | [PostCSS Loader]: 33 | 34 | ```js 35 | module.exports = config => { 36 | require('react-app-rewire-postcss')(config, { 37 | plugins: loader => [ 38 | require('postcss-preset-env')() 39 | ] 40 | }); 41 | 42 | return config; 43 | }; 44 | ``` 45 | 46 | Alternatively, you can now use `postcss.config.js` in your React app directory: 47 | 48 | ```js 49 | module.exports = config => { 50 | require('react-app-rewire-postcss')(config, true /* any truthy value will do */); 51 | 52 | return config; 53 | }; 54 | ``` 55 | 56 | ```js 57 | module.exports = { 58 | plugins: { 59 | 'postcss-preset-env': { 60 | stage: 0 61 | } 62 | } 63 | }; 64 | ``` 65 | 66 | And you can leverage [Browserslist] by adding a `.browserslistrc` to your React 67 | app directory: 68 | 69 | 70 | 71 | ```yaml 72 | # browsers we support 73 | 74 | > 2% 75 | not dead 76 | ``` 77 | 78 | --- 79 | 80 | Happy PostCSS’ing! 81 | 82 | [cli-img]: https://img.shields.io/travis/csstools/react-app-rewire-postcss.svg 83 | [cli-url]: https://travis-ci.org/csstools/react-app-rewire-postcss 84 | [git-img]: https://img.shields.io/badge/support-chat-blue.svg 85 | [git-url]: https://gitter.im/postcss/postcss 86 | [npm-img]: https://img.shields.io/npm/v/react-app-rewire-postcss.svg 87 | [npm-url]: https://www.npmjs.com/package/react-app-rewire-postcss 88 | 89 | [Browserslist]: https://github.com/browserslist/browserslist 90 | [Create React App]: https://github.com/facebook/create-react-app 91 | [Gulp PostCSS]: https://github.com/postcss/gulp-postcss 92 | [Grunt PostCSS]: https://github.com/nDmitry/grunt-postcss 93 | [PostCSS]: https://github.com/postcss/postcss 94 | [PostCSS Loader]: https://github.com/postcss/postcss-loader 95 | [React App Rewire PostCSS]: https://github.com/csstools/react-app-rewire-postcss 96 | [React App Rewired]: https://github.com/timarney/react-app-rewired 97 | [rewired]: https://github.com/timarney/react-app-rewired#how-to-rewire-your-create-react-app-project 98 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | export default (config, options) => { 2 | // find any first matching rule that contains postcss-loader 3 | filterPostCSSLoader(config.module.rules).forEach(rule => { 4 | filterPostCSSLoader(rule.oneOf).forEach(oneOf => { 5 | filterPostCSSLoader(oneOf.use || oneOf.loader).forEach(use => { 6 | // use the latest version of postcss-loader 7 | use.loader = require.resolve('postcss-loader'); 8 | 9 | // conditionally replace options with a custom configuration 10 | use.options = options 11 | ? Object.assign({ ident: 'postcss' }, options) 12 | : Object.assign(use.options, options) 13 | }) 14 | }) 15 | }); 16 | 17 | // return the mutated configuration 18 | return config; 19 | }; 20 | 21 | // return a filtered array that includes postcss-loader 22 | const filterPostCSSLoader = array => array.filter(object => JSON.stringify(object).includes('postcss-loader')); 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-app-rewire-postcss", 3 | "version": "4.0.0", 4 | "description": "Configure PostCSS in Create React App without ejecting", 5 | "author": "Jonathan Neal ", 6 | "license": "CC0-1.0", 7 | "repository": "csstools/react-app-rewire-postcss", 8 | "homepage": "https://github.com/csstools/react-app-rewire-postcss#readme", 9 | "bugs": "https://github.com/csstools/react-app-rewire-postcss/issues", 10 | "main": "index.cjs.js", 11 | "module": "index.es.mjs", 12 | "files": [ 13 | "index.cjs.js", 14 | "index.cjs.js.map", 15 | "index.es.mjs", 16 | "index.es.mjs.map" 17 | ], 18 | "scripts": { 19 | "prepublishOnly": "npm test", 20 | "pretest": "rollup -c .rollup.js --silent", 21 | "test": "echo 'Running tests...'; npm run test:js", 22 | "test:js": "eslint *.js --cache --ignore-path .gitignore --quiet" 23 | }, 24 | "engines": { 25 | "node": ">=8.0.0" 26 | }, 27 | "dependencies": { 28 | "postcss-loader": "^3.0.0" 29 | }, 30 | "devDependencies": { 31 | "@babel/core": "7.4.4", 32 | "@babel/preset-env": "7.4.4", 33 | "babel-eslint": "10.0.1", 34 | "eslint": "5.16.0", 35 | "eslint-config-dev": "2.0.0", 36 | "pre-commit": "1.2.2", 37 | "rollup": "1.11.3", 38 | "rollup-plugin-babel": "4.3.2" 39 | }, 40 | "eslintConfig": { 41 | "extends": "dev", 42 | "parser": "babel-eslint" 43 | }, 44 | "keywords": [ 45 | "react", 46 | "create-react-app", 47 | "react-app-rewire", 48 | "rewire", 49 | "postcss", 50 | "postcss-loader", 51 | "postcss-plugin", 52 | "css" 53 | ] 54 | } 55 | -------------------------------------------------------------------------------- /test-cra1/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /test-cra1/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md). 5 | 6 | ## Table of Contents 7 | 8 | - [Updating to New Releases](#updating-to-new-releases) 9 | - [Sending Feedback](#sending-feedback) 10 | - [Folder Structure](#folder-structure) 11 | - [Available Scripts](#available-scripts) 12 | - [npm start](#npm-start) 13 | - [npm test](#npm-test) 14 | - [npm run build](#npm-run-build) 15 | - [npm run eject](#npm-run-eject) 16 | - [Supported Browsers](#supported-browsers) 17 | - [Supported Language Features](#supported-language-features) 18 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 19 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 20 | - [Debugging in the Editor](#debugging-in-the-editor) 21 | - [Formatting Code Automatically](#formatting-code-automatically) 22 | - [Changing the Page ``](#changing-the-page-title) 23 | - [Installing a Dependency](#installing-a-dependency) 24 | - [Importing a Component](#importing-a-component) 25 | - [Code Splitting](#code-splitting) 26 | - [Adding a Stylesheet](#adding-a-stylesheet) 27 | - [Adding a CSS Modules Stylesheet](#adding-a-css-modules-stylesheet) 28 | - [Adding a Sass Stylesheet](#adding-a-sass-stylesheet) 29 | - [Post-Processing CSS](#post-processing-css) 30 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) 31 | - [Adding SVGs](#adding-svgs) 32 | - [Using the `public` Folder](#using-the-public-folder) 33 | - [Changing the HTML](#changing-the-html) 34 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 35 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 36 | - [Using Global Variables](#using-global-variables) 37 | - [Adding Bootstrap](#adding-bootstrap) 38 | - [Using a Custom Theme](#using-a-custom-theme) 39 | - [Adding Flow](#adding-flow) 40 | - [Adding a Router](#adding-a-router) 41 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 42 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 43 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 44 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 45 | - [Can I Use Decorators?](#can-i-use-decorators) 46 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) 47 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 48 | - [Node](#node) 49 | - [Ruby on Rails](#ruby-on-rails) 50 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 51 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) 52 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 53 | - [Using HTTPS in Development](#using-https-in-development) 54 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 55 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 56 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 57 | - [Running Tests](#running-tests) 58 | - [Filename Conventions](#filename-conventions) 59 | - [Command Line Interface](#command-line-interface) 60 | - [Version Control Integration](#version-control-integration) 61 | - [Writing Tests](#writing-tests) 62 | - [Testing Components](#testing-components) 63 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 64 | - [Initializing Test Environment](#initializing-test-environment) 65 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 66 | - [Coverage Reporting](#coverage-reporting) 67 | - [Continuous Integration](#continuous-integration) 68 | - [Disabling jsdom](#disabling-jsdom) 69 | - [Snapshot Testing](#snapshot-testing) 70 | - [Editor Integration](#editor-integration) 71 | - [Debugging Tests](#debugging-tests) 72 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome) 73 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) 74 | - [Developing Components in Isolation](#developing-components-in-isolation) 75 | - [Getting Started with Storybook](#getting-started-with-storybook) 76 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 77 | - [Publishing Components to npm](#publishing-components-to-npm) 78 | - [Making a Progressive Web App](#making-a-progressive-web-app) 79 | - [Why Opt-in?](#why-opt-in) 80 | - [Offline-First Considerations](#offline-first-considerations) 81 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 82 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 83 | - [Deployment](#deployment) 84 | - [Static Server](#static-server) 85 | - [Other Solutions](#other-solutions) 86 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 87 | - [Building for Relative Paths](#building-for-relative-paths) 88 | - [Customizing Environment Variables for Arbitrary Build Environments](#customizing-environment-variables-for-arbitrary-build-environments) 89 | - [Azure](#azure) 90 | - [Firebase](#firebase) 91 | - [GitHub Pages](#github-pages) 92 | - [Heroku](#heroku) 93 | - [Netlify](#netlify) 94 | - [Now](#now) 95 | - [S3 and CloudFront](#s3-and-cloudfront) 96 | - [Surge](#surge) 97 | - [Advanced Configuration](#advanced-configuration) 98 | - [Troubleshooting](#troubleshooting) 99 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 100 | - [`npm test` hangs or crashes on macOS Sierra](#npm-test-hangs-or-crashes-on-macos-sierra) 101 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 102 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 103 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) 104 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 105 | - [Alternatives to Ejecting](#alternatives-to-ejecting) 106 | - [Something Missing?](#something-missing) 107 | 108 | ## Updating to New Releases 109 | 110 | Create React App is divided into two packages: 111 | 112 | - `create-react-app` is a global command-line utility that you use to create new projects. 113 | - `react-scripts` is a development dependency in the generated projects (including this one). 114 | 115 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 116 | 117 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 118 | 119 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 120 | 121 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` (or `yarn install`) in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 122 | 123 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 124 | 125 | ## Sending Feedback 126 | 127 | We are always open to [your feedback](https://github.com/facebook/create-react-app/issues). 128 | 129 | ## Folder Structure 130 | 131 | After creation, your project should look like this: 132 | 133 | ``` 134 | my-app/ 135 | README.md 136 | node_modules/ 137 | package.json 138 | public/ 139 | index.html 140 | favicon.ico 141 | src/ 142 | App.css 143 | App.js 144 | App.test.js 145 | index.css 146 | index.js 147 | logo.svg 148 | ``` 149 | 150 | For the project to build, **these files must exist with exact filenames**: 151 | 152 | - `public/index.html` is the page template; 153 | - `src/index.js` is the JavaScript entry point. 154 | 155 | You can delete or rename the other files. 156 | 157 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 158 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 159 | 160 | Only files inside `public` can be used from `public/index.html`.<br> 161 | Read instructions below for using assets from JavaScript and HTML. 162 | 163 | You can, however, create more top-level directories.<br> 164 | They will not be included in the production build so you can use them for things like documentation. 165 | 166 | ## Available Scripts 167 | 168 | In the project directory, you can run: 169 | 170 | ### `npm start` 171 | 172 | Runs the app in the development mode.<br> 173 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 174 | 175 | The page will reload if you make edits.<br> 176 | You will also see any lint errors in the console. 177 | 178 | ### `npm test` 179 | 180 | Launches the test runner in the interactive watch mode.<br> 181 | See the section about [running tests](#running-tests) for more information. 182 | 183 | ### `npm run build` 184 | 185 | Builds the app for production to the `build` folder.<br> 186 | It correctly bundles React in production mode and optimizes the build for the best performance. 187 | 188 | The build is minified and the filenames include the hashes.<br> 189 | Your app is ready to be deployed! 190 | 191 | See the section about [deployment](#deployment) for more information. 192 | 193 | ### `npm run eject` 194 | 195 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 196 | 197 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 198 | 199 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 200 | 201 | 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. 202 | 203 | ## Supported Browsers 204 | 205 | By default, the generated project supports all modern browsers.<br> 206 | Support for Internet Explorer 9, 10, and 11 requires [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md). 207 | 208 | ### Supported Language Features 209 | 210 | This project supports a superset of the latest JavaScript standard.<br> 211 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 212 | 213 | - [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 214 | - [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 215 | - [Object Rest/Spread Properties](https://github.com/tc39/proposal-object-rest-spread) (ES2018). 216 | - [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 217 | - [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal). 218 | - [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flow.org/) syntax. 219 | 220 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 221 | 222 | 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. 223 | 224 | Note that **this project includes no [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md)** by default. 225 | 226 | 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](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md), or that the browsers you are targeting already support them. 227 | 228 | ## Syntax Highlighting in the Editor 229 | 230 | 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. 231 | 232 | ## Displaying Lint Output in the Editor 233 | 234 | > Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 235 | > It also only works with npm 3 or higher. 236 | 237 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 238 | 239 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 240 | 241 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 242 | 243 | ```js 244 | { 245 | "extends": "react-app" 246 | } 247 | ``` 248 | 249 | Now your editor should report the linting warnings. 250 | 251 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. 252 | 253 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 254 | 255 | ## Debugging in the Editor 256 | 257 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** 258 | 259 | 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. 260 | 261 | ### Visual Studio Code 262 | 263 | 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. 264 | 265 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 266 | 267 | ```json 268 | { 269 | "version": "0.2.0", 270 | "configurations": [ 271 | { 272 | "name": "Chrome", 273 | "type": "chrome", 274 | "request": "launch", 275 | "url": "http://localhost:3000", 276 | "webRoot": "${workspaceRoot}/src", 277 | "sourceMapPathOverrides": { 278 | "webpack:///src/*": "${webRoot}/*" 279 | } 280 | } 281 | ] 282 | } 283 | ``` 284 | 285 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 286 | 287 | 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. 288 | 289 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). 290 | 291 | ### WebStorm 292 | 293 | 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. 294 | 295 | 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. 296 | 297 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 298 | 299 | 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. 300 | 301 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. 302 | 303 | ## Formatting Code Automatically 304 | 305 | 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/). 306 | 307 | To format our code whenever we make a commit in git, we need to install the following dependencies: 308 | 309 | ```sh 310 | npm install --save husky lint-staged prettier 311 | ``` 312 | 313 | Alternatively you may use `yarn`: 314 | 315 | ```sh 316 | yarn add husky lint-staged prettier 317 | ``` 318 | 319 | - `husky` makes it easy to use githooks as if they are npm scripts. 320 | - `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). 321 | - `prettier` is the JavaScript formatter we will run before commits. 322 | 323 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 324 | 325 | Add the following field to the `package.json` section: 326 | 327 | ```diff 328 | + "husky": { 329 | + "hooks": { 330 | + "pre-commit": "lint-staged" 331 | + } 332 | + } 333 | ``` 334 | 335 | Next we add a 'lint-staged' field to the `package.json`, for example: 336 | 337 | ```diff 338 | "dependencies": { 339 | // ... 340 | }, 341 | + "lint-staged": { 342 | + "src/**/*.{js,jsx,json,css}": [ 343 | + "prettier --single-quote --write", 344 | + "git add" 345 | + ] 346 | + }, 347 | "scripts": { 348 | ``` 349 | 350 | 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. 351 | 352 | 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. 353 | 354 | ## Changing the Page `<title>` 355 | 356 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 357 | 358 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. 359 | 360 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. 361 | 362 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). 363 | 364 | ## Installing a Dependency 365 | 366 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: 367 | 368 | ```sh 369 | npm install --save react-router-dom 370 | ``` 371 | 372 | Alternatively you may use `yarn`: 373 | 374 | ```sh 375 | yarn add react-router-dom 376 | ``` 377 | 378 | This works for any library, not just `react-router-dom`. 379 | 380 | ## Importing a Component 381 | 382 | This project setup supports ES6 modules thanks to Webpack.<br> 383 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. 384 | 385 | For example: 386 | 387 | ### `Button.js` 388 | 389 | ```js 390 | import React, { Component } from 'react'; 391 | 392 | class Button extends Component { 393 | render() { 394 | // ... 395 | } 396 | } 397 | 398 | export default Button; // Don’t forget to use export default! 399 | ``` 400 | 401 | ### `DangerButton.js` 402 | 403 | ```js 404 | import React, { Component } from 'react'; 405 | import Button from './Button'; // Import a component from another file 406 | 407 | class DangerButton extends Component { 408 | render() { 409 | return <Button color="red" />; 410 | } 411 | } 412 | 413 | export default DangerButton; 414 | ``` 415 | 416 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. 417 | 418 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. 419 | 420 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. 421 | 422 | Learn more about ES6 modules: 423 | 424 | - [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) 425 | - [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 426 | - [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 427 | 428 | ## Code Splitting 429 | 430 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. 431 | 432 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. 433 | 434 | Here is an example: 435 | 436 | ### `moduleA.js` 437 | 438 | ```js 439 | const moduleA = 'Hello'; 440 | 441 | export { moduleA }; 442 | ``` 443 | 444 | ### `App.js` 445 | 446 | ```js 447 | import React, { Component } from 'react'; 448 | 449 | class App extends Component { 450 | handleClick = () => { 451 | import('./moduleA') 452 | .then(({ moduleA }) => { 453 | // Use moduleA 454 | }) 455 | .catch(err => { 456 | // Handle failure 457 | }); 458 | }; 459 | 460 | render() { 461 | return ( 462 | <div> 463 | <button onClick={this.handleClick}>Load</button> 464 | </div> 465 | ); 466 | } 467 | } 468 | 469 | export default App; 470 | ``` 471 | 472 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 473 | 474 | You can also use it with `async` / `await` syntax if you prefer it. 475 | 476 | ### With React Router 477 | 478 | 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). 479 | 480 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. 481 | 482 | ## Adding a Stylesheet 483 | 484 | 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**: 485 | 486 | ### `Button.css` 487 | 488 | ```css 489 | .Button { 490 | padding: 20px; 491 | } 492 | ``` 493 | 494 | ### `Button.js` 495 | 496 | ```js 497 | import React, { Component } from 'react'; 498 | import './Button.css'; // Tell Webpack that Button.js uses these styles 499 | 500 | class Button extends Component { 501 | render() { 502 | // You can use them as regular CSS styles 503 | return <div className="Button" />; 504 | } 505 | } 506 | ``` 507 | 508 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-blog/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 509 | 510 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. 511 | 512 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. 513 | 514 | ## Adding a CSS Modules Stylesheet 515 | 516 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 517 | 518 | This project supports [CSS Modules](https://github.com/css-modules/css-modules) alongside regular stylesheets using the `[name].module.css` file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format `[filename]\_[classname]\_\_[hash]`. 519 | 520 | > **Tip:** Should you want to preprocess a stylesheet with Sass then make sure to [follow the installation instructions](#adding-a-sass-stylesheet) and then change the stylesheet file extension as follows: `[name].module.scss` or `[name].module.sass`. 521 | 522 | CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules [here](https://css-tricks.com/css-modules-part-1-need/). 523 | 524 | ### `Button.module.css` 525 | 526 | ```css 527 | .error { 528 | background-color: red; 529 | } 530 | ``` 531 | 532 | ### `another-stylesheet.css` 533 | 534 | ```css 535 | .error { 536 | color: red; 537 | } 538 | ``` 539 | 540 | ### `Button.js` 541 | 542 | ```js 543 | import React, { Component } from 'react'; 544 | import styles from './Button.module.css'; // Import css modules stylesheet as styles 545 | import './another-stylesheet.css'; // Import regular stylesheet 546 | 547 | class Button extends Component { 548 | render() { 549 | // reference as a js object 550 | return <button className={styles.error}>Error Button</button>; 551 | } 552 | } 553 | ``` 554 | 555 | ### Result 556 | 557 | No clashes from other `.error` class names 558 | 559 | ```html 560 | <!-- This button has red background but not red text --> 561 | <button class="Button_error_ax7yz"></div> 562 | ``` 563 | 564 | **This is an optional feature.** Regular `<link>` stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the `.module.css` extension. 565 | 566 | ## Adding a Sass Stylesheet 567 | 568 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 569 | 570 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 571 | 572 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. 573 | 574 | To use Sass, first install `node-sass`: 575 | 576 | ```bash 577 | $ npm install node-sass --save 578 | $ # or 579 | $ yarn add node-sass 580 | ``` 581 | 582 | Now you can rename `src/App.css` to `src/App.scss` and update `src/App.js` to import `src/App.scss`. 583 | This file and any other file will be automatically compiled if imported with the extension `.scss` or `.sass`. 584 | 585 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 586 | 587 | This will allow you to do imports like 588 | 589 | ```scss 590 | @import 'styles/_colors.scss'; // assuming a styles directory under src/ 591 | @import '~nprogress/nprogress'; // importing a css file from the nprogress node module 592 | ``` 593 | 594 | > **Tip:** You can opt into using this feature with [CSS modules](#adding-a-css-modules-stylesheet) too! 595 | 596 | > **Note:** You must prefix imports from `node_modules` with `~` as displayed above. 597 | 598 | ## Post-Processing CSS 599 | 600 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. 601 | 602 | Support for new CSS features like the [`all` property](https://developer.mozilla.org/en-US/docs/Web/CSS/all), [`break` properties](https://www.w3.org/TR/css-break-3/#breaking-controls), [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables), and [media query ranges](https://www.w3.org/TR/mediaqueries-4/#range-context) are automatically polyfilled to add support for older browsers. 603 | 604 | You can customize your target support browsers by adjusting the `browserslist` key in `package.json` accoring to the [Browserslist specification](https://github.com/browserslist/browserslist#readme). 605 | 606 | For example, this: 607 | 608 | ```css 609 | .App { 610 | display: flex; 611 | flex-direction: row; 612 | align-items: center; 613 | } 614 | ``` 615 | 616 | becomes this: 617 | 618 | ```css 619 | .App { 620 | display: -webkit-box; 621 | display: -ms-flexbox; 622 | display: flex; 623 | -webkit-box-orient: horizontal; 624 | -webkit-box-direction: normal; 625 | -ms-flex-direction: row; 626 | flex-direction: row; 627 | -webkit-box-align: center; 628 | -ms-flex-align: center; 629 | align-items: center; 630 | } 631 | ``` 632 | 633 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 634 | 635 | [CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) prefixing is disabled by default, but it will **not** strip manual prefixing. 636 | If you'd like to opt-in to CSS Grid prefixing, [first familiarize yourself about its limitations](https://github.com/postcss/autoprefixer#does-autoprefixer-polyfill-grid-layout-for-ie).<br> 637 | To enable CSS Grid prefixing, add `/* autoprefixer grid: on */` to the top of your CSS file. 638 | 639 | ## Adding Images, Fonts, and Files 640 | 641 | With Webpack, using static assets like images and fonts works similarly to CSS. 642 | 643 | You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. 644 | 645 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebook/create-react-app/issues/1153). 646 | 647 | Here is an example: 648 | 649 | ```js 650 | import React from 'react'; 651 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 652 | 653 | console.log(logo); // /logo.84287d09.png 654 | 655 | function Header() { 656 | // Import result is the URL of your image 657 | return <img src={logo} alt="Logo" />; 658 | } 659 | 660 | export default Header; 661 | ``` 662 | 663 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 664 | 665 | This works in CSS too: 666 | 667 | ```css 668 | .Logo { 669 | background-image: url(./logo.png); 670 | } 671 | ``` 672 | 673 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 674 | 675 | Please be advised that this is also a custom feature of Webpack. 676 | 677 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 678 | An alternative way of handling static assets is described in the next section. 679 | 680 | ### Adding SVGs 681 | 682 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 683 | 684 | One way to add SVG files was described in the section above. You can also import SVGs directly as React components. You can use either of the two approaches. In your code it would look like this: 685 | 686 | ```js 687 | import { ReactComponent as Logo } from './logo.svg'; 688 | const App = () => ( 689 | <div> 690 | {/* Logo is an actual React component */} 691 | <Logo /> 692 | </div> 693 | ); 694 | ``` 695 | 696 | This is handy if you don't want to load SVG as a separate file. Don't forget the curly braces in the import! The `ReactComponent` import name is special and tells Create React App that you want a React component that renders an SVG, rather than its filename. 697 | 698 | ## Using the `public` Folder 699 | 700 | > Note: this feature is available with `react-scripts@0.5.0` and higher. 701 | 702 | ### Changing the HTML 703 | 704 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 705 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 706 | 707 | ### Adding Assets Outside of the Module System 708 | 709 | You can also add other assets to the `public` folder. 710 | 711 | Note that we normally encourage you to `import` assets in JavaScript files instead. 712 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 713 | This mechanism provides a number of benefits: 714 | 715 | - Scripts and stylesheets get minified and bundled together to avoid extra network requests. 716 | - Missing files cause compilation errors instead of 404 errors for your users. 717 | - Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 718 | 719 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 720 | 721 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 722 | 723 | Inside `index.html`, you can use it like this: 724 | 725 | ```html 726 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 727 | ``` 728 | 729 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 730 | 731 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 732 | 733 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 734 | 735 | ```js 736 | render() { 737 | // Note: this is an escape hatch and should be used sparingly! 738 | // Normally we recommend using `import` for getting asset URLs 739 | // as described in “Adding Images and Fonts” above this section. 740 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 741 | } 742 | ``` 743 | 744 | Keep in mind the downsides of this approach: 745 | 746 | - None of the files in `public` folder get post-processed or minified. 747 | - Missing files will not be called at compilation time, and will cause 404 errors for your users. 748 | - Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 749 | 750 | ### When to Use the `public` Folder 751 | 752 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 753 | The `public` folder is useful as a workaround for a number of less common cases: 754 | 755 | - You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 756 | - You have thousands of images and need to dynamically reference their paths. 757 | - You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 758 | - Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 759 | 760 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 761 | 762 | ## Using Global Variables 763 | 764 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 765 | 766 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 767 | 768 | ```js 769 | const $ = window.$; 770 | ``` 771 | 772 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 773 | 774 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 775 | 776 | ## Adding Bootstrap 777 | 778 | You don’t have to use [reactstrap](https://reactstrap.github.io/) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 779 | 780 | Install reactstrap and Bootstrap from npm. reactstrap does not include Bootstrap CSS so this needs to be installed as well: 781 | 782 | ```sh 783 | npm install --save reactstrap bootstrap@4 784 | ``` 785 | 786 | Alternatively you may use `yarn`: 787 | 788 | ```sh 789 | yarn add bootstrap@4 reactstrap 790 | ``` 791 | 792 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your `src/index.js` file: 793 | 794 | ```js 795 | import 'bootstrap/dist/css/bootstrap.css'; 796 | // Put any other imports below so that CSS from your 797 | // components takes precedence over default styles. 798 | ``` 799 | 800 | Import required reactstrap components within `src/App.js` file or your custom component files: 801 | 802 | ```js 803 | import { Button } from 'reactstrap'; 804 | ``` 805 | 806 | Now you are ready to use the imported reactstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/zx6658/d9f128cd57ca69e583ea2b5fea074238/raw/a56701c142d0c622eb6c20a457fbc01d708cb485/App.js) redone using reactstrap. 807 | 808 | ### Using a Custom Theme 809 | 810 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 811 | 812 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 813 | As of `react-scripts@2.0.0` you can import `.scss` files. This makes it possible to use a package's built-in Sass variables for global style preferences. 814 | 815 | To customize Bootstrap, create a file called `src/custom.scss` (or similar) and import the Bootstrap source stylesheet. Add any overrides _before_ the imported file(s). You can reference [Bootstrap's documentation](http://getbootstrap.com/docs/4.1/getting-started/theming/#css-variables) for the names of the available variables. 816 | 817 | ```scss 818 | // Override default variables before the import 819 | $body-bg: #000; 820 | 821 | // Import Bootstrap and its default variables 822 | @import '~bootstrap/scss/bootstrap.scss'; 823 | ``` 824 | 825 | > **Note:** You must prefix imports from `node_modules` with `~` as displayed above. 826 | 827 | Finally, import the newly created `.scss` file instead of the default Bootstrap `.css` in the beginning of your `src/index.js` file, for example: 828 | 829 | ```javascript 830 | import './custom.scss'; 831 | ``` 832 | 833 | ## Adding Flow 834 | 835 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 836 | 837 | Recent versions of [Flow](https://flow.org/) work with Create React App projects out of the box. 838 | 839 | To add Flow to a Create React App project, follow these steps: 840 | 841 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 842 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 843 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flow.org/en/docs/config/) in the root directory. 844 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 845 | 846 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 847 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 848 | In the future we plan to integrate it into Create React App even more closely. 849 | 850 | To learn more about Flow, check out [its documentation](https://flow.org/). 851 | 852 | ## Adding a Router 853 | 854 | Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/web/) is the most popular one. 855 | 856 | To add it, run: 857 | 858 | ```sh 859 | npm install --save react-router-dom 860 | ``` 861 | 862 | Alternatively you may use `yarn`: 863 | 864 | ```sh 865 | yarn add react-router-dom 866 | ``` 867 | 868 | 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. 869 | 870 | 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. 871 | 872 | ## Adding Custom Environment Variables 873 | 874 | > Note: this feature is available with `react-scripts@0.2.3` and higher. 875 | 876 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 877 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 878 | `REACT_APP_`. 879 | 880 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 881 | 882 | > 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/facebook/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 883 | 884 | These environment variables will be defined for you on `process.env`. For example, having an environment 885 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 886 | 887 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 888 | 889 | These environment variables can be useful for displaying information conditionally based on where the project is 890 | deployed or consuming sensitive data that lives outside of version control. 891 | 892 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 893 | in the environment inside a `<form>`: 894 | 895 | ```jsx 896 | render() { 897 | return ( 898 | <div> 899 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 900 | <form> 901 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 902 | </form> 903 | </div> 904 | ); 905 | } 906 | ``` 907 | 908 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 909 | 910 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 911 | 912 | ```html 913 | <div> 914 | <small>You are running this application in <b>development</b> mode.</small> 915 | <form> 916 | <input type="hidden" value="abcdef" /> 917 | </form> 918 | </div> 919 | ``` 920 | 921 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 922 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 923 | a `.env` file. Both of these ways are described in the next few sections. 924 | 925 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 926 | 927 | ```js 928 | if (process.env.NODE_ENV !== 'production') { 929 | analytics.disable(); 930 | } 931 | ``` 932 | 933 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 934 | 935 | ### Referencing Environment Variables in the HTML 936 | 937 | > Note: this feature is available with `react-scripts@0.9.0` and higher. 938 | 939 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 940 | 941 | ```html 942 | <title>%REACT_APP_WEBSITE_NAME% 943 | ``` 944 | 945 | Note that the caveats from the above section apply: 946 | 947 | - Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 948 | - The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 949 | 950 | ### Adding Temporary Environment Variables In Your Shell 951 | 952 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 953 | life of the shell session. 954 | 955 | #### Windows (cmd.exe) 956 | 957 | ```cmd 958 | set "REACT_APP_SECRET_CODE=abcdef" && npm start 959 | ``` 960 | 961 | (Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) 962 | 963 | #### Windows (Powershell) 964 | 965 | ```Powershell 966 | ($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) 967 | ``` 968 | 969 | #### Linux, macOS (Bash) 970 | 971 | ```bash 972 | REACT_APP_SECRET_CODE=abcdef npm start 973 | ``` 974 | 975 | ### Adding Development Environment Variables In `.env` 976 | 977 | > Note: this feature is available with `react-scripts@0.5.0` and higher. 978 | 979 | To define permanent environment variables, create a file called `.env` in the root of your project: 980 | 981 | ``` 982 | REACT_APP_SECRET_CODE=abcdef 983 | ``` 984 | 985 | > 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/facebook/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 986 | 987 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 988 | 989 | #### What other `.env` files can be used? 990 | 991 | > Note: this feature is **available with `react-scripts@1.0.0` and higher**. 992 | 993 | - `.env`: Default. 994 | - `.env.local`: Local overrides. **This file is loaded for all environments except test.** 995 | - `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 996 | - `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 997 | 998 | Files on the left have more priority than files on the right: 999 | 1000 | - `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 1001 | - `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 1002 | - `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 1003 | 1004 | These variables will act as the defaults if the machine does not explicitly set them.
1005 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 1006 | 1007 | > Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 1008 | > 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). 1009 | 1010 | #### Expanding Environment Variables In `.env` 1011 | 1012 | > Note: this feature is available with `react-scripts@1.1.0` and higher. 1013 | 1014 | Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). 1015 | 1016 | For example, to get the environment variable `npm_package_version`: 1017 | 1018 | ``` 1019 | REACT_APP_VERSION=$npm_package_version 1020 | # also works: 1021 | # REACT_APP_VERSION=${npm_package_version} 1022 | ``` 1023 | 1024 | Or expand variables local to the current `.env` file: 1025 | 1026 | ``` 1027 | DOMAIN=www.example.com 1028 | REACT_APP_FOO=$DOMAIN/foo 1029 | REACT_APP_BAR=$DOMAIN/bar 1030 | ``` 1031 | 1032 | ## Can I Use Decorators? 1033 | 1034 | Some popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
1035 | Create React App intentionally doesn’t support decorator syntax at the moment because: 1036 | 1037 | - It is an experimental proposal and is subject to change (in fact, it has already changed once, and will change again). 1038 | - Most libraries currently support only the old version of the proposal — which will never be a standard. 1039 | 1040 | However in many cases you can rewrite decorator-based code without decorators just as fine.
1041 | Please refer to these two threads for reference: 1042 | 1043 | - [#214](https://github.com/facebook/create-react-app/issues/214) 1044 | - [#411](https://github.com/facebook/create-react-app/issues/411) 1045 | 1046 | Create React App will add decorator support when the specification advances to a stable stage. 1047 | 1048 | ## Fetching Data with AJAX Requests 1049 | 1050 | 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. 1051 | 1052 | The global `fetch` function allows you to easily make 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). 1053 | 1054 | 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. 1055 | 1056 | Make sure the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) are available in your target audience's browsers. 1057 | For example, support in Internet Explorer requires a [polyfill](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md). 1058 | 1059 | 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). 1060 | 1061 | ## Integrating with an API Backend 1062 | 1063 | These tutorials will help you to integrate your app with an API backend running on another port, 1064 | using `fetch()` to access it. 1065 | 1066 | ### Node 1067 | 1068 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 1069 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 1070 | 1071 | ### Ruby on Rails 1072 | 1073 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 1074 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 1075 | 1076 | ### API Platform (PHP and Symfony) 1077 | 1078 | [API Platform](https://api-platform.com) is a framework designed to build API-driven projects. 1079 | It allows to create hypermedia and GraphQL APIs in minutes. 1080 | It is shipped with an official Progressive Web App generator as well as a dynamic administration interface, both built for Create React App. 1081 | Check out [this tutorial](https://api-platform.com/docs/distribution). 1082 | 1083 | ## Proxying API Requests in Development 1084 | 1085 | > Note: this feature is available with `react-scripts@0.2.3` and higher. 1086 | 1087 | People often serve the front-end React app from the same host and port as their backend implementation.
1088 | For example, a production setup might look like this after the app is deployed: 1089 | 1090 | ``` 1091 | / - static server returns index.html with React app 1092 | /todos - static server returns index.html with React app 1093 | /api/todos - server handles any /api/* requests using the backend implementation 1094 | ``` 1095 | 1096 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 1097 | 1098 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 1099 | 1100 | ```js 1101 | "proxy": "http://localhost:4000", 1102 | ``` 1103 | 1104 | 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. 1105 | 1106 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 1107 | 1108 | ``` 1109 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 1110 | ``` 1111 | 1112 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 1113 | 1114 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
1115 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 1116 | 1117 | - [Configure the proxy yourself](#configuring-the-proxy-manually) 1118 | - Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 1119 | - Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 1120 | 1121 | ### "Invalid Host Header" Errors After Configuring Proxy 1122 | 1123 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 1124 | 1125 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebook/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 1126 | 1127 | > Invalid Host header 1128 | 1129 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 1130 | 1131 | ``` 1132 | HOST=mypublicdevhost.com 1133 | ``` 1134 | 1135 | If you restart the development server now and load the app from the specified host, it should work. 1136 | 1137 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 1138 | 1139 | ``` 1140 | # NOTE: THIS IS DANGEROUS! 1141 | # It exposes your machine to attacks from the websites you visit. 1142 | DANGEROUSLY_DISABLE_HOST_CHECK=true 1143 | ``` 1144 | 1145 | We don’t recommend this approach. 1146 | 1147 | ### Configuring the Proxy Manually 1148 | 1149 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 1150 | 1151 | If the `proxy` option is **not** flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware. 1152 | 1153 | You can use this feature in conjunction with the `proxy` property in `package.json`, but it is recommended you consolidate all of your logic into `src/setupProxy.js`. 1154 | 1155 | First, install `http-proxy-middleware` using npm or Yarn: 1156 | 1157 | ```bash 1158 | $ npm install http-proxy-middleware --save 1159 | $ # or 1160 | $ yarn add http-proxy-middleware 1161 | ``` 1162 | 1163 | Next, create `src/setupProxy.js` and place the following contents in it: 1164 | 1165 | ```js 1166 | const proxy = require('http-proxy-middleware'); 1167 | 1168 | module.exports = function(app) { 1169 | // ... 1170 | }; 1171 | ``` 1172 | 1173 | You can now register proxies as you wish! Here's an example using the above `http-proxy-middleware`: 1174 | 1175 | ```js 1176 | const proxy = require('http-proxy-middleware'); 1177 | 1178 | module.exports = function(app) { 1179 | app.use(proxy('/api', { target: 'http://localhost:5000/' })); 1180 | }; 1181 | ``` 1182 | 1183 | > **Note:** You do not need to import this file anywhere. It is automatically registered when you start the development server. 1184 | 1185 | > **Note:** This file only supports Node's JavaScript syntax. Be sure to only use supported language features (i.e. no support for Flow, ES Modules, etc). 1186 | 1187 | ## Using HTTPS in Development 1188 | 1189 | > Note: this feature is available with `react-scripts@0.4.0` and higher. 1190 | 1191 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 1192 | 1193 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 1194 | 1195 | #### Windows (cmd.exe) 1196 | 1197 | ```cmd 1198 | set HTTPS=true&&npm start 1199 | ``` 1200 | 1201 | (Note: the lack of whitespace is intentional.) 1202 | 1203 | #### Windows (Powershell) 1204 | 1205 | ```Powershell 1206 | ($env:HTTPS = $true) -and (npm start) 1207 | ``` 1208 | 1209 | #### Linux, macOS (Bash) 1210 | 1211 | ```bash 1212 | HTTPS=true npm start 1213 | ``` 1214 | 1215 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1216 | 1217 | ## Generating Dynamic `` Tags on the Server 1218 | 1219 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1220 | 1221 | ```html 1222 | 1223 | 1224 | 1225 | 1226 | 1227 | ``` 1228 | 1229 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 1230 | 1231 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 1232 | 1233 | ## Pre-Rendering into Static HTML Files 1234 | 1235 | 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. 1236 | 1237 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1238 | 1239 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1240 | 1241 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1242 | 1243 | ## Injecting Data from the Server into the Page 1244 | 1245 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1246 | 1247 | ```js 1248 | 1249 | 1250 | 1251 | 1254 | ``` 1255 | 1256 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 1257 | 1258 | ## Running Tests 1259 | 1260 | > Note: this feature is available with `react-scripts@0.3.0` and higher.
1261 | 1262 | > [Read the migration guide to learn how to enable it in older projects!](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 1263 | 1264 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 1265 | 1266 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 1267 | 1268 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 1269 | 1270 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 1271 | 1272 | ### Filename Conventions 1273 | 1274 | Jest will look for test files with any of the following popular naming conventions: 1275 | 1276 | - Files with `.js` suffix in `__tests__` folders. 1277 | - Files with `.test.js` suffix. 1278 | - Files with `.spec.js` suffix. 1279 | 1280 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1281 | 1282 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 1283 | 1284 | ### Command Line Interface 1285 | 1286 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 1287 | 1288 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 1289 | 1290 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1291 | 1292 | ### Version Control Integration 1293 | 1294 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 1295 | 1296 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 1297 | 1298 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 1299 | 1300 | ### Writing Tests 1301 | 1302 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 1303 | 1304 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1305 | 1306 | ```js 1307 | import sum from './sum'; 1308 | 1309 | it('sums numbers', () => { 1310 | expect(sum(1, 2)).toEqual(3); 1311 | expect(sum(2, 2)).toEqual(4); 1312 | }); 1313 | ``` 1314 | 1315 | All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
1316 | 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. 1317 | 1318 | ### Testing Components 1319 | 1320 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 1321 | 1322 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 1323 | 1324 | ```js 1325 | import React from 'react'; 1326 | import ReactDOM from 'react-dom'; 1327 | import App from './App'; 1328 | 1329 | it('renders without crashing', () => { 1330 | const div = document.createElement('div'); 1331 | ReactDOM.render(, div); 1332 | }); 1333 | ``` 1334 | 1335 | 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`. 1336 | 1337 | 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. 1338 | 1339 | 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: 1340 | 1341 | ```sh 1342 | npm install --save enzyme enzyme-adapter-react-16 react-test-renderer 1343 | ``` 1344 | 1345 | Alternatively you may use `yarn`: 1346 | 1347 | ```sh 1348 | yarn add enzyme enzyme-adapter-react-16 react-test-renderer 1349 | ``` 1350 | 1351 | 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.) 1352 | 1353 | The adapter will also need to be configured in your [global setup file](#initializing-test-environment): 1354 | 1355 | #### `src/setupTests.js` 1356 | 1357 | ```js 1358 | import { configure } from 'enzyme'; 1359 | import Adapter from 'enzyme-adapter-react-16'; 1360 | 1361 | configure({ adapter: new Adapter() }); 1362 | ``` 1363 | 1364 | > 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. 1365 | 1366 | Now you can write a smoke test with it: 1367 | 1368 | ```js 1369 | import React from 'react'; 1370 | import { shallow } from 'enzyme'; 1371 | import App from './App'; 1372 | 1373 | it('renders without crashing', () => { 1374 | shallow(); 1375 | }); 1376 | ``` 1377 | 1378 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `