├── .cache └── 325c8f456729b912b0d2134054eb7448-dfeeb2271cc2857eb0a45a5003c8bbee ├── .gitignore ├── .storybook ├── addons.js └── config.js ├── LICENSE ├── README.md ├── lerna.json ├── package-lock.json ├── package.json ├── packages ├── comp-button │ ├── dist │ │ └── index.js │ ├── package.json │ └── src │ │ ├── index.js │ │ ├── index.spec.js │ │ └── index.stories.js └── my-react-app │ ├── .gitignore │ ├── README.md │ ├── 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 │ └── yarn.lock └── setupTests.js /.cache/325c8f456729b912b0d2134054eb7448-dfeeb2271cc2857eb0a45a5003c8bbee: -------------------------------------------------------------------------------- 1 | {"value":{"success":true,"data":{"latest":{"version":"3.4.11","info":{"plain":"If you see this message in your terminal, please open a GitHub issue"}}},"time":1540604489474},"type":"Object"} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | .DS_Store -------------------------------------------------------------------------------- /.storybook/addons.js: -------------------------------------------------------------------------------- 1 | import '@storybook/addon-actions/register'; 2 | import '@storybook/addon-links/register'; 3 | -------------------------------------------------------------------------------- /.storybook/config.js: -------------------------------------------------------------------------------- 1 | import { configure } from '@storybook/react'; 2 | 3 | // automatically import all files ending in *.stories.js 4 | const req = require.context('../packages', true, /.stories.js$/); 5 | function loadStories() { 6 | req.keys().forEach(filename => req(filename)); 7 | } 8 | 9 | configure(loadStories, module); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Alistair MacDonald 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Guide - React-App Monorepo with Lerna 2 | 3 | > In this guide you will learn how to scaffold a Monorepo to manage multiple React Apps that share common components. 4 | 5 | Featuring: 6 | 7 | - [Lerna] - The Monorepo manager 8 | - [Create-React-App-2] - React 16 App Scaffolding (unejected) 9 | - [Storybook-4-React] - Component Storybook 10 | - [Jest] - Unit/Snapshot Testing 11 | - [Babel-Loader-Lerna-CRA] - Auto-transpile sibling Lerna modules 12 | 13 | > Note: Download the code for this guide from GitHub [f1lt3r/monorepo-react](https://github.com/F1LT3R/monorepo-react). 14 | 15 | > ### ⚠️ IMPORTANT STEPS 16 | > If you are checking out this code to test without using this guide, please remember to follow these important steps in order: 17 | > 18 | > 1. `npm install` in Lerna root directory 19 | > 2. `npm install` in the `packages/my-react-app` directory 20 | > 3. `npx babel-loader-lerna-cra` in the Lerna root directory 21 | 22 | # The Case For Monorepos 23 | 24 | Imagine a scenario where you are building a suite of three React apps that share the same architecture, design patterns, components and styles. Now imaging making an update to a low-level component like a Button that is used in all three apps, as well as one sub-component. 25 | 26 | ![Multi React App Monorepo dependency graph](https://i.imgur.com/rPs8Vmf.png) 27 | 28 | In this scenario, you would be forced into a process like this: 29 | 30 | 1. Update the Button code in the Button's git respository. (`Component #B` in the diagram above) 31 | 1. Create a Pull Requst in the `Component #B` repo and get the new code into `master`. 32 | 2. Publish the `Component #B` Button code on a public or private NPM service. 33 | 2. Go into React `Component #C` repo that uses the Button and update the `package.json` dependancies. 34 | 1. Create a second Pull Request in the `Component #C`, repo and get that new code into `master`. 35 | 2. Publish the component to the NPM repo. 36 | 3. Go into `React App #1` 37 | 1. Update the dependencies. 38 | 2. Republish the package on npm service. 39 | 3. Submit a new PR. 40 | 4. Deploy 41 | 4. Go into `React App #2` 42 | 1. Update the dependencies. 43 | 2. Republish the package on npm service. 44 | 3. Submit a new PR. 45 | 4. Deploy 46 | 5. Go into `React App #3` 47 | 1. Update the dependencies. 48 | 2. Republish the package on npm service. 49 | 3. Submit a new PR. 50 | 4. Deploy 51 | 52 | That is five pull requests for a change to one button component! 53 | 54 | Clearly this is less than ideal. 55 | 56 | ## A Simpler Solution 57 | 58 | Now imagine using a single repo for the same update. If we use a Monorepo tool like [Lerna], the update process will look more like this: 59 | 60 | 1. Update the Button code in the Button's git directory. (`Component #B` in the diagram above) 61 | 2. Run `lerna bootstrap` to crosslink the Button `Component #B` into all the sub dependancies. 62 | 3. Run `lerna publish` to update the packages in your privite NPM service. 63 | 4. Create a Pull Requst in the `Monorepo` repo and get the new code into `master`. 64 | 5. Re-deploy the apps with the updated `package.json` version numbers. 65 | 66 | Now everything is done in one Pull Request. 67 | 68 | This is why large organizations like Facebook and Google make good use of Monorepos. This process can be simplified to use a single shared repo for all the depenencies and apps. The Monorepo scales up without losing as much engineering velocity and reduces human error lost from switching contexual focus. 69 | 70 | The following guide will show you how to set up a such Monorepo for a React project. 71 | 72 | # Prerequisites 73 | 74 | ```shell 75 | $ npm i -g lerna 76 | ``` 77 | 78 | ```shell 79 | $ npm i -g create-react-app 80 | ``` 81 | 82 | Create a directory for your Monorepo project. 83 | 84 | ```shell 85 | $ cd ~/repos 86 | $ mkdir monorepo-react 87 | $ cd monorepo-react 88 | ``` 89 | 90 | # Setup Lerna 91 | 92 | > Note: In order restart these this guide at any time, you remove the following files and directories: 93 | > ```shell 94 | > $ sudo rm -r node_modules packages stories .storybook coverage stories 95 | > $ rm package.json package-lock.json setupTests.js lerna.json 96 | > ``` 97 | 98 | 99 | Create and initialize your [Lerna] monorepo: 100 | 101 | ```shell 102 | $ lerna init 103 | ``` 104 | 105 | Your `package.json` should now look like this: 106 | 107 | ```json 108 | { 109 | "name": "root", 110 | "private": true, 111 | "devDependencies": { 112 | "lerna": "^3.4.3" 113 | } 114 | } 115 | ``` 116 | 117 | # Install Common Depenencies 118 | 119 | Installing these common dependencies will allow you to: 120 | 121 | - Run Storybook for the root of your project. 122 | - To have Storybook auto-install the right modules for your React project. 123 | - Have Babel transpile correctly for code, testing and Storybook. 124 | 125 | ```shell 126 | $ npm i -D react react-dom @babel/core@^7.0.0-0 @babel/cli babel-plugin-transform-es2015-modules-commonjs babel-jest enzyme enzyme-adapter-react-16 jest react-test-renderer babel-core@7.0.0-bridge.0 @babel/preset-env @babel/preset-react 127 | ``` 128 | 129 | Your `package.json` should now look like this: 130 | 131 | ```json 132 | { 133 | "name": "root", 134 | "private": true, 135 | "devDependencies": { 136 | "@babel/cli": "^7.1.2", 137 | "@babel/core": "^7.1.2", 138 | "@babel/preset-env": "^7.1.0", 139 | "@babel/preset-react": "^7.0.0", 140 | "babel-core": "^7.0.0-bridge.0", 141 | "babel-jest": "^23.6.0", 142 | "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", 143 | "enzyme": "^3.7.0", 144 | "enzyme-adapter-react-16": "^1.6.0", 145 | "jest": "^23.6.0", 146 | "lerna": "^3.4.3", 147 | "react": "^16.6.0", 148 | "react-dom": "^16.6.0", 149 | "react-test-renderer": "^16.6.0" 150 | } 151 | } 152 | ``` 153 | 154 | # Install Storybook React 155 | 156 | Now we will install and initialize Storybook version 4. 157 | 158 | ```shell 159 | $ npx -p @storybook/cli@alpha sb init 160 | ``` 161 | 162 | Note: Installing the `@alpha` version (currently `@4.0.0-rc.6`), will allow us to set our Babel configuration inside of our `package.json` files which will make configuration easier for sub-packages. 163 | 164 | ![Screenshot of Storybook React 4 installing](https://imgur.com/Tquu6YT.png) 165 | 166 | Your root `package.json` file should now look like this: 167 | 168 | ```json 169 | { 170 | "name": "root", 171 | "private": true, 172 | "devDependencies": { 173 | "@babel/cli": "^7.1.2", 174 | "@babel/core": "^7.1.2", 175 | "@babel/preset-env": "^7.1.0", 176 | "@babel/preset-react": "^7.0.0", 177 | "babel-core": "^7.0.0-bridge.0", 178 | "babel-jest": "^23.6.0", 179 | "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", 180 | "enzyme": "^3.7.0", 181 | "enzyme-adapter-react-16": "^1.6.0", 182 | "jest": "^23.6.0", 183 | "lerna": "^3.4.3", 184 | "react": "^16.6.0", 185 | "react-dom": "^16.6.0", 186 | "react-test-renderer": "^16.6.0", 187 | "@storybook/react": "^4.0.0-alpha.25", 188 | "@storybook/addon-actions": "^4.0.0-alpha.25", 189 | "@storybook/addon-links": "^4.0.0-alpha.25", 190 | "@storybook/addons": "^4.0.0-alpha.25", 191 | "babel-loader": "^8.0.4" 192 | }, 193 | "dependencies": {}, 194 | "scripts": { 195 | "storybook": "start-storybook -p 6006", 196 | "build-storybook": "build-storybook" 197 | } 198 | } 199 | ``` 200 | 201 | Now you can test that Storybook runs on your machine. 202 | 203 | ```shell 204 | $ npm run storybook 205 | ``` 206 | 207 | ![Screenshot of Storybook React 4 launching from the command line](https://imgur.com/gFzGOfJ.png) 208 | 209 | Storybook should now launch in your web browser automatically. 210 | 211 | ![Screenshot of Storybook running in the web browser](https://i.imgur.com/SaYF4x6.png) 212 | 213 | List the storybook files: 214 | 215 | ```shell 216 | $ tree -C .storybook stories 217 | ``` 218 | 219 | - Your `.storybook/` directory contains your Storybook configuration. 220 | - Your `stories/` directory is where your global Storybook stories live. 221 | 222 | ![Screenshot of .storybook and stories directories](https://imgur.com/m5xzkiZ.png) 223 | 224 | > Note: To install tree: [`brew`/`apt-get`/`yum`/`pkg`] `install tree` 225 | 226 | # Create Your React App 227 | 228 | Create a home in `packages/my-react-app` for your React App. 229 | 230 | ```shell 231 | $ cd ~/repos/monorepo-react/packages/ 232 | $ create-react-app my-react-app 233 | ``` 234 | 235 | Run your React app to test things worked. 236 | 237 | ```shell 238 | $ cd my-react-app 239 | $ npm run start 240 | ``` 241 | 242 | You should now see an error message about Webpack like this one: 243 | 244 | ![Screenshot of React error message about Webpack version number](https://imgur.com/5XOdevS.png) 245 | 246 | We will work around this by setting the `SKIP_PREFLIGHT_CHECK=true` in the `.env` file as suggested. 247 | 248 | ```shell 249 | echo "SKIP_PREFLIGHT_CHECK=true" > .env 250 | ``` 251 | 252 | You should now be able to run your React app, and your browser should launch automatically. 253 | 254 | ```shell 255 | $ npm run start 256 | ``` 257 | 258 | ![Screenshot of Your React App running in the web browser](https://i.imgur.com/yovfAHZ.png) 259 | 260 | ## Create an External React Component 261 | 262 | Lets create our first external React component. We will do this inside our `./packages` directory provided by Lerna. 263 | 264 | ```shell 265 | $ cd ~/repos/monorepo-react/packages/ 266 | $ mkdir comp-button 267 | $ cd comp-button 268 | ``` 269 | 270 | Create a `packages/comp-button/package.json` file like this: 271 | 272 | ```json 273 | { 274 | "name": "@project/comp-button", 275 | "version": "0.1.0", 276 | "description": "A simple button component", 277 | "main": "dist/index.js", 278 | "module": "src/index.js", 279 | "scripts": { 280 | "transpile": "babel src -d dist --ignore '**/*.spec.js,**/*.stories.js'", 281 | "jest": "jest --coverage --verbose --color" 282 | }, 283 | "babel": { 284 | "presets": [ 285 | "@babel/preset-env", 286 | "@babel/preset-react" 287 | ], 288 | "env": { 289 | "test": { 290 | "plugins": [ 291 | "transform-es2015-modules-commonjs" 292 | ] 293 | } 294 | } 295 | } 296 | } 297 | ``` 298 | 299 | What is going on in the `package.json` file: 300 | 301 | - `name`: The organizational namespace for your component when installed via NPM or cross-linked Lerna. 302 | - `main`: The the compiled code that will be shipped with the build of your React app. 303 | - `module`: The pre-compiled code that will be imported as a local run-time dependency while developing the app or running tests. 304 | - `transpile`: An NPM script start the transpile of your code with Babel. **Note:** We are not using `build` because we want to reserve this word later to build our React apps with `lerna run build`. 305 | - `babel`: This setup configures our component to transpile with Babel 7 for React. 306 | 307 | > Note: Because we installed components like `react`, `react-dom`, `@babel/core@^7.0.0-0` in our root `package.json` we do not have to install them again in this package. 308 | 309 | Make a source directory for your React component. 310 | 311 | ```shell 312 | $ mkdir src 313 | $ cd src 314 | ``` 315 | 316 | Create your React component in `packages/comp-button/index.js`: 317 | 318 | ```jsx 319 | import React from 'react' 320 | 321 | const Button = ({ type = 'button', children, onClick }) => ( 322 |
323 | 326 |
327 | ) 328 | 329 | export default Button 330 | ``` 331 | 332 | ## Transpile Your Component 333 | 334 | Now lets try to transpile your React code to ECMAScript 2015 (JavaScript with support for older browsers). 335 | 336 | ```shell 337 | $ lerna run transpile 338 | ``` 339 | 340 | You should see the following output: 341 | 342 | ![Screenshot of babel transpiling button component](https://imgur.com/YDkWQ3T.png) 343 | 344 | Your `./dist/` directory should now contain the transpiled `index.js` file: 345 | 346 | ```shell 347 | $ tree -C ../dist 348 | ``` 349 | 350 | ![SCreenshot of the "dist" directory listing](https://imgur.com/qIeoay7.png) 351 | 352 | The `./dist/index.js` file should contain your transpiled code, like this: 353 | 354 | ```js 355 | "use strict"; 356 | 357 | Object.defineProperty(exports, "__esModule", { 358 | value: true 359 | }); 360 | exports.default = void 0; 361 | 362 | var _react = _interopRequireDefault(require("react")); 363 | 364 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 365 | 366 | var Button = function Button(_ref) { 367 | var _ref$type = _ref.type, 368 | type = _ref$type === void 0 ? 'button' : _ref$type, 369 | children = _ref.children, 370 | onClick = _ref.onClick; 371 | return _react.default.createElement("div", null, _react.default.createElement("button", { 372 | type: type, 373 | className: "button", 374 | onClick: onClick 375 | }, children)); 376 | }; 377 | 378 | var _default = Button; 379 | exports.default = _default; 380 | ``` 381 | 382 | ## Test Your Component 383 | 384 | While we are here, lets create a Jest spec for your component in `packages/comp-button/src/index.spec.js`: 385 | 386 | ```jsx 387 | import React from 'react'; 388 | import {mount} from 'enzyme'; 389 | import Button from '.'; 390 | 391 | describe('Button Component', function() { 392 | it('renders without props', function() { 393 | const wrapper = mount( 409 | ); 410 | 411 | const child = wrapper.find('.child') 412 | expect(child.length).toBe(1) 413 | }) 414 | 415 | it('handles onClick events', () => { 416 | const onClick = jest.fn() 417 | const wrapper = mount( 418 | 514 | )) 515 | 516 | .add('with some emoji', () => ( 517 | 518 | )) 519 | 520 | .add('with a theme provider', () => ( 521 | 522 | )) 523 | ``` 524 | **Reconfigure Storybook** 525 | 526 | We will now need to configure Storybook to load stories from all the `packages/**` directories, instead of loading `stories/` from your Monorepo root. 527 | 528 | Edit your Storybook configuration in `~/repos/monorepo-react/.storybook/config.js`, so it look like this: 529 | 530 | ```js 531 | import { configure } from '@storybook/react'; 532 | 533 | // automatically import all files ending in *.stories.js 534 | const req = require.context('../packages', true, /.stories.js$/); 535 | function loadStories() { 536 | req.keys().forEach(filename => req(filename)); 537 | } 538 | 539 | configure(loadStories, module); 540 | ``` 541 | 542 | It's now safe to delete the `stories/` directory at the Monorepo root. 543 | 544 | ```shell 545 | $ cd ~/repos/monorepo-react/ 546 | $ sudo rm -r stories 547 | ``` 548 | 549 | Lets check that the Storybook still loads with your `comp-button` Story: 550 | 551 | ```shell 552 | $ npm run storybook 553 | ``` 554 | 555 | You should now be able to see your button component Story which was built from your `packages/comp-button` directory: 556 | 557 | ![Screenshot of Storybook displaying your Button component Story](https://imgur.com/YLqC2Fi.png) 558 | 559 | # Crosslink Your Dependencies with Lerna 560 | 561 | Add the following dependency to your `packages/my-react-app/package.json`: 562 | 563 | ```json 564 | { 565 | "dependencies": { 566 | "@my-project/comp-button": "*" 567 | } 568 | } 569 | ``` 570 | 571 | Your `packages/my-react-app/package.json` should now look like this: 572 | 573 | ```json 574 | { 575 | "name": "@my-project/my-react-app", 576 | "version": "0.1.0", 577 | "private": true, 578 | "dependencies": { 579 | "react": "^16.6.0", 580 | "react-dom": "^16.6.0", 581 | "react-scripts": "2.0.5", 582 | "@my-project/comp-button": "*" 583 | }, 584 | "scripts": { 585 | "start": "react-scripts start", 586 | "build": "react-scripts build", 587 | "test": "react-scripts test", 588 | "eject": "react-scripts eject" 589 | }, 590 | "eslintConfig": { 591 | "extends": "react-app" 592 | }, 593 | "browserslist": [ 594 | ">0.2%", 595 | "not dead", 596 | "not ie <= 11", 597 | "not op_mini all" 598 | ] 599 | } 600 | ``` 601 | 602 | We can now crosslink our packages using `lerna bootstrap`. 603 | 604 | ```shell 605 | $ lerna bootstrap 606 | ``` 607 | 608 | You should see the following success message: 609 | 610 | ![Screenshot of the Lerna Bootstrap success message](https://imgur.com/XZzyCaw.png) 611 | 612 | # Use Your Component in The React App 613 | 614 | Add the follow lines to `packages/my-react-app/src/App.js`: 615 | 616 | ```jsx 617 | import CompButton from '@my-project/comp-button'; 618 | Foobar! 619 | ``` 620 | 621 | Your file will now look like this: 622 | 623 | ```jsx 624 | import React, { Component } from 'react'; 625 | import logo from './logo.svg'; 626 | import './App.css'; 627 | import CompButton from '@my-project/comp-button'; 628 | 629 | class App extends Component { 630 | render() { 631 | return ( 632 |
633 |
634 | logo 635 |

636 | Edit src/App.js and save to reload. 637 |

638 | 644 | Learn React 645 | 646 | Foobar! 647 |
648 |
649 | ); 650 | } 651 | } 652 | 653 | export default App; 654 | ``` 655 | 656 | Now start your app: 657 | 658 | ```shell 659 | $ npm run start 660 | ``` 661 | 662 | You should see the following error: 663 | 664 | ![Screenshot of React Start error](https://imgur.com/LfNmtHp.png) 665 | 666 | The React App is failing to compile because Create-React-App's Webpack config is unaware of the any external modules. This means Webpack can not tell Babel-Loader about your component directories, and the sources do not get transpiled. 667 | 668 | It seems like this will problem may go away with future versions of Create-React-App, although this may require Yarn Workspaces. So make sure you check the GitHub Issue [Create-React-App-Lerna-Support] to see if this feature os landed before using the following work-around. 669 | 670 | # Rewire Your React App for Lerna 671 | 672 | I created a small Work-around Node Module to override Create-React-App Webpack configs inside Lerna projects, called [Babel-Loader-Lerna-CRA]. It's pretty simple. It just updates the Webpack paths for Babel-Loader. 673 | 674 | You can install this package using NPM: 675 | 676 | ```shell 677 | npm i -D babel-loader-lerna-cra 678 | ``` 679 | 680 | Now lets update the `package.json` in our Lerna root with glob patterns that describe the relationship between our components and our app. 681 | 682 | ```json 683 | "babel-loader-lerna-cra": { 684 | "imports": "packages/comp-*/src", 685 | "apps": "packages/*react-app*" 686 | } 687 | ``` 688 | 689 | Your `package.json` should now look like this: 690 | 691 | ```json 692 | { 693 | "name": "root", 694 | "private": true, 695 | "devDependencies": { 696 | "@babel/cli": "^7.1.2", 697 | "@babel/core": "^7.1.2", 698 | "@babel/preset-env": "^7.1.0", 699 | "@babel/preset-react": "^7.0.0", 700 | "@storybook/addon-actions": "^4.0.0-alpha.25", 701 | "@storybook/addon-links": "^4.0.0-alpha.25", 702 | "@storybook/addons": "^4.0.0-alpha.25", 703 | "@storybook/react": "^4.0.0-alpha.25", 704 | "babel-core": "^7.0.0-bridge.0", 705 | "babel-jest": "^23.6.0", 706 | "babel-loader": "^8.0.4", 707 | "babel-loader-lerna-cra": "^0.1.2", 708 | "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", 709 | "enzyme": "^3.7.0", 710 | "enzyme-adapter-react-16": "^1.6.0", 711 | "jest": "^23.6.0", 712 | "lerna": "^3.4.3", 713 | "react": "^16.6.0", 714 | "react-dom": "^16.6.0", 715 | "react-test-renderer": "^16.6.0" 716 | }, 717 | "dependencies": {}, 718 | "scripts": { 719 | "storybook": "start-storybook -p 6006", 720 | "build-storybook": "build-storybook" 721 | }, 722 | "babel-loader-lerna-cra": { 723 | "imports": "packages/comp-*/src", 724 | "apps": "packages/*react-app*" 725 | } 726 | } 727 | ``` 728 | 729 | - The **`imports`** refer to components that the React app will neeed to transpile. 730 | - The **`apps`** inform `babel-loader-lerna-cra` where the Webpack overrides will need to happen. 731 | 732 | Now lets bootstrap the Webpack configs in our React app with `babel-loader-lerna-cra`: 733 | 734 | ```shell 735 | $ npx babel-loader-lerna-cra 736 | ``` 737 | 738 | You should see the following output: 739 | 740 | ![Screenshot of babel-loader-lerna-cra bootstrapping Create-React-App's Webpack config in the CLI](https://imgur.com/zpGHfZY.png) 741 | 742 | Now lets try running your React App again: 743 | 744 | ```shell 745 | $ cd ~/repos/monorepo-react/packages/my-react-app 746 | $ npm run start 747 | ``` 748 | 749 | You should now see the React App launch in a browser with your `CompButton` component rendering with the text "Foorbar!" 750 | 751 | ![Screenshot of the React app running with a Lerna sibling component](https://imgur.com/gBfC9IH.png) 752 | 753 | ## So what did we get out of this work-around? 754 | 755 | - **Auto Transpilation of Lerna Siblings** 756 | 757 | Our React App can now import sibling Lerna depedencies and transpile then when needed. 758 | 759 | - **React App Hot Reloading** 760 | 761 | When we change our React component file, will hot-update the app without having to add any global watchers to the Lerna project to kick of a transpile. 762 | 763 | Here is our `CompButton` component being Hot-Reloaded as it is being updated: 764 | 765 | ![Five second animated screencast of Hot Reloading using babel-loeader-lerna-cra](https://imgur.com/ukPvQbS.gif) 766 | 767 | - **Storybook Hot Reloading** 768 | 769 | Nothing special here, but it's worth noting that our Storybook still hot-reloads too. 770 | 771 | ![Screenshot of Storybook after hot-reloading our Button component](https://imgur.com/qrtY6qd.png) 772 | 773 | # Conclusion 774 | 775 | I think this is as far as I would like to take this in a single article. I hope someone else finds this setup useful. If people express interest, I will follow up with a Part 2 on how to setup CI to ship multiple React Apps from this Monorepo setup. 776 | 777 | 778 | Comments, feedback, suggestions always welcome! 779 | 780 | Always ready to learn. 781 | 782 | — Alistair MacDonald 783 | 784 | # Interesting Articles on This Topic: 785 | - https://medium.com/@luisvieira_gmr/building-large-scale-react-applications-in-a-monorepo-91cd4637c131 786 | - https://cacm.acm.org/magazines/2016/7/204032-why-google-stores-billions-of-lines-of-code-in-a-single-repository/fulltext 787 | - https://github.com/facebook/create-react-app/issues/1333 788 | - https://github.com/facebook/create-react-app/pull/3741 789 | - https://github.com/jamiebuilds/react-loadable 790 | - https://daveceddia.com/customize-create-react-app-webpack-without-ejecting/ 791 | 792 | --- 793 | [Lerna]: https://lernajs.io/ "Lerna" 794 | [Create-React-App-2]: https://github.com/facebook/create-react-app "Create React App" 795 | [Jest]: https://jestjs.io/ "Jest" 796 | [Storybook-4-React]: https://github.com/storybooks/storybook/tree/master/app/react "Storybook React" 797 | [Create-React-App-Lerna-Support]: https://github.com/facebook/create-react-app/issues/1333 "Create-React-App Lerna Support" 798 | [Babel-Loader-Lerna-CRA]: https://www.npmjs.com/package/babel-loader-lerna-cra "Babel-Loader Lerna CRA" 799 | -------------------------------------------------------------------------------- /lerna.json: -------------------------------------------------------------------------------- 1 | { 2 | "packages": [ 3 | "packages/*" 4 | ], 5 | "version": "0.0.0" 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "root", 3 | "private": true, 4 | "devDependencies": { 5 | "@babel/cli": "^7.1.2", 6 | "@babel/core": "^7.1.2", 7 | "@babel/preset-env": "^7.1.0", 8 | "@babel/preset-react": "^7.0.0", 9 | "@storybook/addon-actions": "^4.0.0-alpha.25", 10 | "@storybook/addon-links": "^4.0.0-alpha.25", 11 | "@storybook/addons": "^4.0.0-alpha.25", 12 | "@storybook/react": "^4.0.0-alpha.25", 13 | "babel-core": "^7.0.0-bridge.0", 14 | "babel-jest": "^23.6.0", 15 | "babel-loader": "^8.0.4", 16 | "babel-loader-lerna-cra": "^0.1.3", 17 | "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2", 18 | "enzyme": "^3.7.0", 19 | "enzyme-adapter-react-16": "^1.6.0", 20 | "jest": "^23.6.0", 21 | "lerna": "^3.4.3", 22 | "react": "^16.6.0", 23 | "react-dom": "^16.6.0", 24 | "react-test-renderer": "^16.6.0" 25 | }, 26 | "dependencies": {}, 27 | "scripts": { 28 | "storybook": "start-storybook -p 6006", 29 | "build-storybook": "build-storybook" 30 | }, 31 | "babel-loader-lerna-cra": { 32 | "imports": "packages/comp-*/src", 33 | "apps": "packages/*react-app*" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /packages/comp-button/dist/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | Object.defineProperty(exports, "__esModule", { 4 | value: true 5 | }); 6 | exports.default = void 0; 7 | 8 | var _react = _interopRequireDefault(require("react")); 9 | 10 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 11 | 12 | var Button = function Button(_ref) { 13 | var _ref$type = _ref.type, 14 | type = _ref$type === void 0 ? 'button' : _ref$type, 15 | children = _ref.children, 16 | onClick = _ref.onClick; 17 | return _react.default.createElement("div", null, _react.default.createElement("button", { 18 | type: type, 19 | className: "button", 20 | onClick: onClick 21 | }, children)); 22 | }; 23 | 24 | var _default = Button; 25 | exports.default = _default; -------------------------------------------------------------------------------- /packages/comp-button/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@my-project/comp-button", 3 | "version": "0.1.0", 4 | "description": "A simple button component", 5 | "main": "dist/index.js", 6 | "module": "src/index.js", 7 | "scripts": { 8 | "transpile": "babel src -d dist --ignore '**/*.spec.js,**/*.stories.js'", 9 | "jest": "jest --coverage --verbose --color" 10 | }, 11 | "babel": { 12 | "presets": [ 13 | "@babel/preset-env", 14 | "@babel/preset-react" 15 | ], 16 | "env": { 17 | "test": { 18 | "plugins": [ 19 | "transform-es2015-modules-commonjs" 20 | ] 21 | } 22 | } 23 | }, 24 | "jest": { 25 | "setupFiles": [ 26 | "../../setupTests" 27 | ] 28 | } 29 | } -------------------------------------------------------------------------------- /packages/comp-button/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | const Button = ({ type = 'button', children, onClick }) => ( 4 |
5 | 8 |
9 | ) 10 | 11 | export default Button -------------------------------------------------------------------------------- /packages/comp-button/src/index.spec.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {mount} from 'enzyme'; 3 | import Button from '.'; 4 | 5 | describe('Button Component', function() { 6 | it('renders without props', function() { 7 | const wrapper = mount( 23 | ); 24 | 25 | const child = wrapper.find('.child') 26 | expect(child.length).toBe(1) 27 | }) 28 | 29 | it('handles onClick events', () => { 30 | const onClick = jest.fn() 31 | const wrapper = mount( 32 | 11 | )) 12 | 13 | .add('with some emoji', () => ( 14 | 15 | )) 16 | 17 | .add('with a theme provider', () => ( 18 | 19 | )) -------------------------------------------------------------------------------- /packages/my-react-app/.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 | -------------------------------------------------------------------------------- /packages/my-react-app/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 Relay](#adding-relay) 41 | - [Adding a Router](#adding-a-router) 42 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 43 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 44 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 45 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 46 | - [Can I Use Decorators?](#can-i-use-decorators) 47 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) 48 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 49 | - [Node](#node) 50 | - [Ruby on Rails](#ruby-on-rails) 51 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 52 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) 53 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 54 | - [Using HTTPS in Development](#using-https-in-development) 55 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 56 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 57 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 58 | - [Running Tests](#running-tests) 59 | - [Filename Conventions](#filename-conventions) 60 | - [Command Line Interface](#command-line-interface) 61 | - [Version Control Integration](#version-control-integration) 62 | - [Writing Tests](#writing-tests) 63 | - [Testing Components](#testing-components) 64 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 65 | - [Initializing Test Environment](#initializing-test-environment) 66 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 67 | - [Coverage Reporting](#coverage-reporting) 68 | - [Continuous Integration](#continuous-integration) 69 | - [Disabling jsdom](#disabling-jsdom) 70 | - [Snapshot Testing](#snapshot-testing) 71 | - [Editor Integration](#editor-integration) 72 | - [Debugging Tests](#debugging-tests) 73 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome) 74 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) 75 | - [Developing Components in Isolation](#developing-components-in-isolation) 76 | - [Getting Started with Storybook](#getting-started-with-storybook) 77 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 78 | - [Publishing Components to npm](#publishing-components-to-npm) 79 | - [Making a Progressive Web App](#making-a-progressive-web-app) 80 | - [Why Opt-in?](#why-opt-in) 81 | - [Offline-First Considerations](#offline-first-considerations) 82 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 83 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 84 | - [Deployment](#deployment) 85 | - [Static Server](#static-server) 86 | - [Other Solutions](#other-solutions) 87 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 88 | - [Building for Relative Paths](#building-for-relative-paths) 89 | - [Customizing Environment Variables for Arbitrary Build Environments](#customizing-environment-variables-for-arbitrary-build-environments) 90 | - [Azure](#azure) 91 | - [Firebase](#firebase) 92 | - [GitHub Pages](#github-pages) 93 | - [Heroku](#heroku) 94 | - [Netlify](#netlify) 95 | - [Now](#now) 96 | - [S3 and CloudFront](#s3-and-cloudfront) 97 | - [Surge](#surge) 98 | - [Advanced Configuration](#advanced-configuration) 99 | - [Troubleshooting](#troubleshooting-1) 100 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 101 | - [`npm test` hangs or crashes on macOS Sierra](#npm-test-hangs-or-crashes-on-macos-sierra) 102 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 103 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 104 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) 105 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 106 | - [Alternatives to Ejecting](#alternatives-to-ejecting) 107 | - [Something Missing?](#something-missing) 108 | 109 | ## Updating to New Releases 110 | 111 | Create React App is divided into two packages: 112 | 113 | - `create-react-app` is a global command-line utility that you use to create new projects. 114 | - `react-scripts` is a development dependency in the generated projects (including this one). 115 | 116 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 117 | 118 | 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. 119 | 120 | 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. 121 | 122 | 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. 123 | 124 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 125 | 126 | ## Sending Feedback 127 | 128 | We are always open to [your feedback](https://github.com/facebook/create-react-app/issues). 129 | 130 | ## Folder Structure 131 | 132 | After creation, your project should look like this: 133 | 134 | ``` 135 | my-app/ 136 | README.md 137 | node_modules/ 138 | package.json 139 | public/ 140 | index.html 141 | favicon.ico 142 | src/ 143 | App.css 144 | App.js 145 | App.test.js 146 | index.css 147 | index.js 148 | logo.svg 149 | ``` 150 | 151 | For the project to build, **these files must exist with exact filenames**: 152 | 153 | - `public/index.html` is the page template; 154 | - `src/index.js` is the JavaScript entry point. 155 | 156 | You can delete or rename the other files. 157 | 158 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 159 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 160 | 161 | Only files inside `public` can be used from `public/index.html`.<br> 162 | Read instructions below for using assets from JavaScript and HTML. 163 | 164 | You can, however, create more top-level directories.<br> 165 | They will not be included in the production build so you can use them for things like documentation. 166 | 167 | If you have Git installed and your project is not part of a larger repository, then a new repository will be initialized resulting in an additional `.git/` top-level directory. 168 | 169 | ## Available Scripts 170 | 171 | In the project directory, you can run: 172 | 173 | ### `npm start` 174 | 175 | Runs the app in the development mode.<br> 176 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 177 | 178 | The page will reload if you make edits.<br> 179 | You will also see any lint errors in the console. 180 | 181 | ### `npm test` 182 | 183 | Launches the test runner in the interactive watch mode.<br> 184 | See the section about [running tests](#running-tests) for more information. 185 | 186 | ### `npm run build` 187 | 188 | Builds the app for production to the `build` folder.<br> 189 | It correctly bundles React in production mode and optimizes the build for the best performance. 190 | 191 | The build is minified and the filenames include the hashes.<br> 192 | Your app is ready to be deployed! 193 | 194 | See the section about [deployment](#deployment) for more information. 195 | 196 | ### `npm run eject` 197 | 198 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 199 | 200 | 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. 201 | 202 | 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. 203 | 204 | 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. 205 | 206 | ## Supported Browsers 207 | 208 | By default, the generated project supports all modern browsers.<br> 209 | 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). 210 | 211 | ### Supported Language Features 212 | 213 | This project supports a superset of the latest JavaScript standard.<br> 214 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 215 | 216 | - [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 217 | - [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 218 | - [Object Rest/Spread Properties](https://github.com/tc39/proposal-object-rest-spread) (ES2018). 219 | - [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 220 | - [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal). 221 | - [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flow.org/) syntax. 222 | 223 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 224 | 225 | 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. 226 | 227 | Note that **this project includes no [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md)** by default. 228 | 229 | 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. 230 | 231 | ## Syntax Highlighting in the Editor 232 | 233 | 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. 234 | 235 | ## Displaying Lint Output in the Editor 236 | 237 | > Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 238 | > It also only works with npm 3 or higher. 239 | 240 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 241 | 242 | 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. 243 | 244 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 245 | 246 | ```js 247 | { 248 | "extends": "react-app" 249 | } 250 | ``` 251 | 252 | Now your editor should report the linting warnings. 253 | 254 | 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. 255 | 256 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 257 | 258 | ## Debugging in the Editor 259 | 260 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** 261 | 262 | 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. 263 | 264 | ### Visual Studio Code 265 | 266 | 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. 267 | 268 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 269 | 270 | ```json 271 | { 272 | "version": "0.2.0", 273 | "configurations": [ 274 | { 275 | "name": "Chrome", 276 | "type": "chrome", 277 | "request": "launch", 278 | "url": "http://localhost:3000", 279 | "webRoot": "${workspaceRoot}/src", 280 | "sourceMapPathOverrides": { 281 | "webpack:///src/*": "${webRoot}/*" 282 | } 283 | } 284 | ] 285 | } 286 | ``` 287 | 288 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 289 | 290 | 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. 291 | 292 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). 293 | 294 | ### WebStorm 295 | 296 | 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. 297 | 298 | 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. 299 | 300 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 301 | 302 | 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. 303 | 304 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. 305 | 306 | ## Formatting Code Automatically 307 | 308 | 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/). 309 | 310 | To format our code whenever we make a commit in git, we need to install the following dependencies: 311 | 312 | ```sh 313 | npm install --save husky lint-staged prettier 314 | ``` 315 | 316 | Alternatively you may use `yarn`: 317 | 318 | ```sh 319 | yarn add husky lint-staged prettier 320 | ``` 321 | 322 | - `husky` makes it easy to use githooks as if they are npm scripts. 323 | - `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). 324 | - `prettier` is the JavaScript formatter we will run before commits. 325 | 326 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 327 | 328 | Add the following field to the `package.json` section: 329 | 330 | ```diff 331 | + "husky": { 332 | + "hooks": { 333 | + "pre-commit": "lint-staged" 334 | + } 335 | + } 336 | ``` 337 | 338 | Next we add a 'lint-staged' field to the `package.json`, for example: 339 | 340 | ```diff 341 | "dependencies": { 342 | // ... 343 | }, 344 | + "lint-staged": { 345 | + "src/**/*.{js,jsx,json,css}": [ 346 | + "prettier --single-quote --write", 347 | + "git add" 348 | + ] 349 | + }, 350 | "scripts": { 351 | ``` 352 | 353 | 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. 354 | 355 | 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. 356 | 357 | ## Changing the Page `<title>` 358 | 359 | 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. 360 | 361 | 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. 362 | 363 | 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. 364 | 365 | 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). 366 | 367 | ## Installing a Dependency 368 | 369 | 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`: 370 | 371 | ```sh 372 | npm install --save react-router-dom 373 | ``` 374 | 375 | Alternatively you may use `yarn`: 376 | 377 | ```sh 378 | yarn add react-router-dom 379 | ``` 380 | 381 | This works for any library, not just `react-router-dom`. 382 | 383 | ## Importing a Component 384 | 385 | This project setup supports ES6 modules thanks to Webpack.<br> 386 | 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. 387 | 388 | For example: 389 | 390 | ### `Button.js` 391 | 392 | ```js 393 | import React, { Component } from 'react'; 394 | 395 | class Button extends Component { 396 | render() { 397 | // ... 398 | } 399 | } 400 | 401 | export default Button; // Don’t forget to use export default! 402 | ``` 403 | 404 | ### `DangerButton.js` 405 | 406 | ```js 407 | import React, { Component } from 'react'; 408 | import Button from './Button'; // Import a component from another file 409 | 410 | class DangerButton extends Component { 411 | render() { 412 | return <Button color="red" />; 413 | } 414 | } 415 | 416 | export default DangerButton; 417 | ``` 418 | 419 | 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. 420 | 421 | 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'`. 422 | 423 | 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. 424 | 425 | Learn more about ES6 modules: 426 | 427 | - [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) 428 | - [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 429 | - [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 430 | 431 | ## Code Splitting 432 | 433 | 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. 434 | 435 | 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. 436 | 437 | Here is an example: 438 | 439 | ### `moduleA.js` 440 | 441 | ```js 442 | const moduleA = 'Hello'; 443 | 444 | export { moduleA }; 445 | ``` 446 | 447 | ### `App.js` 448 | 449 | ```js 450 | import React, { Component } from 'react'; 451 | 452 | class App extends Component { 453 | handleClick = () => { 454 | import('./moduleA') 455 | .then(({ moduleA }) => { 456 | // Use moduleA 457 | }) 458 | .catch(err => { 459 | // Handle failure 460 | }); 461 | }; 462 | 463 | render() { 464 | return ( 465 | <div> 466 | <button onClick={this.handleClick}>Load</button> 467 | </div> 468 | ); 469 | } 470 | } 471 | 472 | export default App; 473 | ``` 474 | 475 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 476 | 477 | You can also use it with `async` / `await` syntax if you prefer it. 478 | 479 | ### With React Router 480 | 481 | 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). 482 | 483 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. 484 | 485 | ## Adding a Stylesheet 486 | 487 | 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**: 488 | 489 | ### `Button.css` 490 | 491 | ```css 492 | .Button { 493 | padding: 20px; 494 | } 495 | ``` 496 | 497 | ### `Button.js` 498 | 499 | ```js 500 | import React, { Component } from 'react'; 501 | import './Button.css'; // Tell Webpack that Button.js uses these styles 502 | 503 | class Button extends Component { 504 | render() { 505 | // You can use them as regular CSS styles 506 | return <div className="Button" />; 507 | } 508 | } 509 | ``` 510 | 511 | **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. 512 | 513 | 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. 514 | 515 | 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. 516 | 517 | ## Adding a CSS Modules Stylesheet 518 | 519 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 520 | 521 | 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]`. 522 | 523 | > **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`. 524 | 525 | 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/). 526 | 527 | ### `Button.module.css` 528 | 529 | ```css 530 | .error { 531 | background-color: red; 532 | } 533 | ``` 534 | 535 | ### `another-stylesheet.css` 536 | 537 | ```css 538 | .error { 539 | color: red; 540 | } 541 | ``` 542 | 543 | ### `Button.js` 544 | 545 | ```js 546 | import React, { Component } from 'react'; 547 | import styles from './Button.module.css'; // Import css modules stylesheet as styles 548 | import './another-stylesheet.css'; // Import regular stylesheet 549 | 550 | class Button extends Component { 551 | render() { 552 | // reference as a js object 553 | return <button className={styles.error}>Error Button</button>; 554 | } 555 | } 556 | ``` 557 | 558 | ### Result 559 | 560 | No clashes from other `.error` class names 561 | 562 | ```html 563 | <!-- This button has red background but not red text --> 564 | <button class="Button_error_ax7yz"></div> 565 | ``` 566 | 567 | **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. 568 | 569 | ## Adding a Sass Stylesheet 570 | 571 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 572 | 573 | 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)). 574 | 575 | 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. 576 | 577 | To use Sass, first install `node-sass`: 578 | 579 | ```bash 580 | $ npm install node-sass --save 581 | $ # or 582 | $ yarn add node-sass 583 | ``` 584 | 585 | Now you can rename `src/App.css` to `src/App.scss` and update `src/App.js` to import `src/App.scss`. 586 | This file and any other file will be automatically compiled if imported with the extension `.scss` or `.sass`. 587 | 588 | 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. 589 | 590 | This will allow you to do imports like 591 | 592 | ```scss 593 | @import 'styles/_colors.scss'; // assuming a styles directory under src/ 594 | @import '~nprogress/nprogress'; // importing a css file from the nprogress node module 595 | ``` 596 | 597 | > **Tip:** You can opt into using this feature with [CSS modules](#adding-a-css-modules-stylesheet) too! 598 | 599 | > **Note:** You must prefix imports from `node_modules` with `~` as displayed above. 600 | 601 | > **Note:** If you're using Flow, add the following to your `.flowconfig` so it'll recognize the `.sass` or `.scss` imports. 602 | 603 | ``` 604 | [options] 605 | module.file_ext=.sass 606 | module.file_ext=.scss 607 | ``` 608 | 609 | ## Post-Processing CSS 610 | 611 | 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. 612 | 613 | 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. 614 | 615 | You can customize your target support browsers by adjusting the `browserslist` key in `package.json` according to the [Browserslist specification](https://github.com/browserslist/browserslist#readme). 616 | 617 | For example, this: 618 | 619 | ```css 620 | .App { 621 | display: flex; 622 | flex-direction: row; 623 | align-items: center; 624 | } 625 | ``` 626 | 627 | becomes this: 628 | 629 | ```css 630 | .App { 631 | display: -webkit-box; 632 | display: -ms-flexbox; 633 | display: flex; 634 | -webkit-box-orient: horizontal; 635 | -webkit-box-direction: normal; 636 | -ms-flex-direction: row; 637 | flex-direction: row; 638 | -webkit-box-align: center; 639 | -ms-flex-align: center; 640 | align-items: center; 641 | } 642 | ``` 643 | 644 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 645 | 646 | [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. 647 | 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> 648 | To enable CSS Grid prefixing, add `/* autoprefixer grid: on */` to the top of your CSS file. 649 | 650 | ## Adding Images, Fonts, and Files 651 | 652 | With Webpack, using static assets like images and fonts works similarly to CSS. 653 | 654 | 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. 655 | 656 | 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). 657 | 658 | Here is an example: 659 | 660 | ```js 661 | import React from 'react'; 662 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 663 | 664 | console.log(logo); // /logo.84287d09.png 665 | 666 | function Header() { 667 | // Import result is the URL of your image 668 | return <img src={logo} alt="Logo" />; 669 | } 670 | 671 | export default Header; 672 | ``` 673 | 674 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 675 | 676 | This works in CSS too: 677 | 678 | ```css 679 | .Logo { 680 | background-image: url(./logo.png); 681 | } 682 | ``` 683 | 684 | 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. 685 | 686 | Please be advised that this is also a custom feature of Webpack. 687 | 688 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 689 | An alternative way of handling static assets is described in the next section. 690 | 691 | ### Adding SVGs 692 | 693 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 694 | 695 | 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: 696 | 697 | ```js 698 | import { ReactComponent as Logo } from './logo.svg'; 699 | const App = () => ( 700 | <div> 701 | {/* Logo is an actual React component */} 702 | <Logo /> 703 | </div> 704 | ); 705 | ``` 706 | 707 | 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. 708 | 709 | ## Using the `public` Folder 710 | 711 | > Note: this feature is available with `react-scripts@0.5.0` and higher. 712 | 713 | ### Changing the HTML 714 | 715 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 716 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 717 | 718 | ### Adding Assets Outside of the Module System 719 | 720 | You can also add other assets to the `public` folder. 721 | 722 | Note that we normally encourage you to `import` assets in JavaScript files instead. 723 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 724 | This mechanism provides a number of benefits: 725 | 726 | - Scripts and stylesheets get minified and bundled together to avoid extra network requests. 727 | - Missing files cause compilation errors instead of 404 errors for your users. 728 | - Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 729 | 730 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 731 | 732 | 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`. 733 | 734 | Inside `index.html`, you can use it like this: 735 | 736 | ```html 737 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 738 | ``` 739 | 740 | 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. 741 | 742 | 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. 743 | 744 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 745 | 746 | ```js 747 | render() { 748 | // Note: this is an escape hatch and should be used sparingly! 749 | // Normally we recommend using `import` for getting asset URLs 750 | // as described in “Adding Images and Fonts” above this section. 751 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 752 | } 753 | ``` 754 | 755 | Keep in mind the downsides of this approach: 756 | 757 | - None of the files in `public` folder get post-processed or minified. 758 | - Missing files will not be called at compilation time, and will cause 404 errors for your users. 759 | - Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 760 | 761 | ### When to Use the `public` Folder 762 | 763 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 764 | The `public` folder is useful as a workaround for a number of less common cases: 765 | 766 | - 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). 767 | - You have thousands of images and need to dynamically reference their paths. 768 | - You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 769 | - Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 770 | 771 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 772 | 773 | ## Using Global Variables 774 | 775 | 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. 776 | 777 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 778 | 779 | ```js 780 | const $ = window.$; 781 | ``` 782 | 783 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 784 | 785 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 786 | 787 | ## Adding Bootstrap 788 | 789 | 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: 790 | 791 | Install reactstrap and Bootstrap from npm. reactstrap does not include Bootstrap CSS so this needs to be installed as well: 792 | 793 | ```sh 794 | npm install --save reactstrap bootstrap@4 795 | ``` 796 | 797 | Alternatively you may use `yarn`: 798 | 799 | ```sh 800 | yarn add bootstrap@4 reactstrap 801 | ``` 802 | 803 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your `src/index.js` file: 804 | 805 | ```js 806 | import 'bootstrap/dist/css/bootstrap.css'; 807 | // Put any other imports below so that CSS from your 808 | // components takes precedence over default styles. 809 | ``` 810 | 811 | Import required reactstrap components within `src/App.js` file or your custom component files: 812 | 813 | ```js 814 | import { Button } from 'reactstrap'; 815 | ``` 816 | 817 | 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. 818 | 819 | ### Using a Custom Theme 820 | 821 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 822 | 823 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 824 | 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. 825 | 826 | 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. 827 | 828 | ```scss 829 | // Override default variables before the import 830 | $body-bg: #000; 831 | 832 | // Import Bootstrap and its default variables 833 | @import '~bootstrap/scss/bootstrap.scss'; 834 | ``` 835 | 836 | > **Note:** You must prefix imports from `node_modules` with `~` as displayed above. 837 | 838 | Finally, import the newly created `.scss` file instead of the default Bootstrap `.css` in the beginning of your `src/index.js` file, for example: 839 | 840 | ```javascript 841 | import './custom.scss'; 842 | ``` 843 | 844 | ## Adding Flow 845 | 846 | 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. 847 | 848 | Recent versions of [Flow](https://flow.org/) work with Create React App projects out of the box. 849 | 850 | To add Flow to a Create React App project, follow these steps: 851 | 852 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 853 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 854 | 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. 855 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 856 | 857 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 858 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 859 | In the future we plan to integrate it into Create React App even more closely. 860 | 861 | To learn more about Flow, check out [its documentation](https://flow.org/). 862 | 863 | ## Adding Relay 864 | 865 | Relay is a framework for building data-driven React applications powered by GraphQL. The current release candidate of Relay works with Create React App projects out of the box using Babel Macros. Simply set up your project as laid out in the [Relay documentation](https://facebook.github.io/relay/), then make sure you have a version of the babel plugin providing the macro. 866 | 867 | To add it, run: 868 | 869 | ```sh 870 | npm install --save --dev babel-plugin-relay@dev 871 | ``` 872 | 873 | Alternatively you may use `yarn`: 874 | 875 | ```sh 876 | yarn upgrade babel-plugin-relay@dev 877 | ``` 878 | 879 | Then, wherever you use the `graphql` template tag, import the macro: 880 | 881 | ```js 882 | import graphql from 'babel-plugin-relay/macro'; 883 | // instead of: 884 | // import { graphql } from "babel-plugin-relay" 885 | 886 | graphql` 887 | query UserQuery { 888 | viewer { 889 | id 890 | } 891 | } 892 | `; 893 | ``` 894 | 895 | To learn more about Relay, check out [its documentation](https://facebook.github.io/relay/). 896 | 897 | ## Adding a Router 898 | 899 | Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/web/) is the most popular one. 900 | 901 | To add it, run: 902 | 903 | ```sh 904 | npm install --save react-router-dom 905 | ``` 906 | 907 | Alternatively you may use `yarn`: 908 | 909 | ```sh 910 | yarn add react-router-dom 911 | ``` 912 | 913 | 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. 914 | 915 | 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. 916 | 917 | ## Adding Custom Environment Variables 918 | 919 | > Note: this feature is available with `react-scripts@0.2.3` and higher. 920 | 921 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 922 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 923 | `REACT_APP_`. 924 | 925 | **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. 926 | 927 | > 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. 928 | 929 | These environment variables will be defined for you on `process.env`. For example, having an environment 930 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 931 | 932 | 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. 933 | 934 | These environment variables can be useful for displaying information conditionally based on where the project is 935 | deployed or consuming sensitive data that lives outside of version control. 936 | 937 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 938 | in the environment inside a `<form>`: 939 | 940 | ```jsx 941 | render() { 942 | return ( 943 | <div> 944 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 945 | <form> 946 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 947 | </form> 948 | </div> 949 | ); 950 | } 951 | ``` 952 | 953 | 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. 954 | 955 | 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`: 956 | 957 | ```html 958 | <div> 959 | <small>You are running this application in <b>development</b> mode.</small> 960 | <form> 961 | <input type="hidden" value="abcdef" /> 962 | </form> 963 | </div> 964 | ``` 965 | 966 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 967 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 968 | a `.env` file. Both of these ways are described in the next few sections. 969 | 970 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 971 | 972 | ```js 973 | if (process.env.NODE_ENV !== 'production') { 974 | analytics.disable(); 975 | } 976 | ``` 977 | 978 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 979 | 980 | ### Referencing Environment Variables in the HTML 981 | 982 | > Note: this feature is available with `react-scripts@0.9.0` and higher. 983 | 984 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 985 | 986 | ```html 987 | <title>%REACT_APP_WEBSITE_NAME% 988 | ``` 989 | 990 | Note that the caveats from the above section apply: 991 | 992 | - Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 993 | - 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). 994 | 995 | ### Adding Temporary Environment Variables In Your Shell 996 | 997 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 998 | life of the shell session. 999 | 1000 | #### Windows (cmd.exe) 1001 | 1002 | ```cmd 1003 | set "REACT_APP_SECRET_CODE=abcdef" && npm start 1004 | ``` 1005 | 1006 | (Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) 1007 | 1008 | #### Windows (Powershell) 1009 | 1010 | ```Powershell 1011 | ($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) 1012 | ``` 1013 | 1014 | #### Linux, macOS (Bash) 1015 | 1016 | ```bash 1017 | REACT_APP_SECRET_CODE=abcdef npm start 1018 | ``` 1019 | 1020 | ### Adding Development Environment Variables In `.env` 1021 | 1022 | > Note: this feature is available with `react-scripts@0.5.0` and higher. 1023 | 1024 | To define permanent environment variables, create a file called `.env` in the root of your project: 1025 | 1026 | ``` 1027 | REACT_APP_SECRET_CODE=abcdef 1028 | ``` 1029 | 1030 | > 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. 1031 | 1032 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 1033 | 1034 | #### What other `.env` files can be used? 1035 | 1036 | > Note: this feature is **available with `react-scripts@1.0.0` and higher**. 1037 | 1038 | - `.env`: Default. 1039 | - `.env.local`: Local overrides. **This file is loaded for all environments except test.** 1040 | - `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 1041 | - `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 1042 | 1043 | Files on the left have more priority than files on the right: 1044 | 1045 | - `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 1046 | - `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 1047 | - `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 1048 | 1049 | These variables will act as the defaults if the machine does not explicitly set them.
1050 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 1051 | 1052 | > Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 1053 | > 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). 1054 | 1055 | #### Expanding Environment Variables In `.env` 1056 | 1057 | > Note: this feature is available with `react-scripts@1.1.0` and higher. 1058 | 1059 | Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). 1060 | 1061 | For example, to get the environment variable `npm_package_version`: 1062 | 1063 | ``` 1064 | REACT_APP_VERSION=$npm_package_version 1065 | # also works: 1066 | # REACT_APP_VERSION=${npm_package_version} 1067 | ``` 1068 | 1069 | Or expand variables local to the current `.env` file: 1070 | 1071 | ``` 1072 | DOMAIN=www.example.com 1073 | REACT_APP_FOO=$DOMAIN/foo 1074 | REACT_APP_BAR=$DOMAIN/bar 1075 | ``` 1076 | 1077 | ## Can I Use Decorators? 1078 | 1079 | Some popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
1080 | Create React App intentionally doesn’t support decorator syntax at the moment because: 1081 | 1082 | - It is an experimental proposal and is subject to change (in fact, it has already changed once, and will change again). 1083 | - Most libraries currently support only the old version of the proposal — which will never be a standard. 1084 | 1085 | However in many cases you can rewrite decorator-based code without decorators just as fine.
1086 | Please refer to these two threads for reference: 1087 | 1088 | - [#214](https://github.com/facebook/create-react-app/issues/214) 1089 | - [#411](https://github.com/facebook/create-react-app/issues/411) 1090 | 1091 | Create React App will add decorator support when the specification advances to a stable stage. 1092 | 1093 | ## Fetching Data with AJAX Requests 1094 | 1095 | 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. 1096 | 1097 | 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). 1098 | 1099 | 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. 1100 | 1101 | 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. 1102 | For example, support in Internet Explorer requires a [polyfill](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md). 1103 | 1104 | 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). 1105 | 1106 | ## Integrating with an API Backend 1107 | 1108 | These tutorials will help you to integrate your app with an API backend running on another port, 1109 | using `fetch()` to access it. 1110 | 1111 | ### Node 1112 | 1113 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 1114 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 1115 | 1116 | ### Ruby on Rails 1117 | 1118 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 1119 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 1120 | 1121 | ### API Platform (PHP and Symfony) 1122 | 1123 | [API Platform](https://api-platform.com) is a framework designed to build API-driven projects. 1124 | It allows to create hypermedia and GraphQL APIs in minutes. 1125 | It is shipped with an official Progressive Web App generator as well as a dynamic administration interface, both built for Create React App. 1126 | Check out [this tutorial](https://api-platform.com/docs/distribution). 1127 | 1128 | ## Proxying API Requests in Development 1129 | 1130 | > Note: this feature is available with `react-scripts@0.2.3` and higher. 1131 | 1132 | People often serve the front-end React app from the same host and port as their backend implementation.
1133 | For example, a production setup might look like this after the app is deployed: 1134 | 1135 | ``` 1136 | / - static server returns index.html with React app 1137 | /todos - static server returns index.html with React app 1138 | /api/todos - server handles any /api/* requests using the backend implementation 1139 | ``` 1140 | 1141 | 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. 1142 | 1143 | 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: 1144 | 1145 | ```js 1146 | "proxy": "http://localhost:4000", 1147 | ``` 1148 | 1149 | 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. 1150 | 1151 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 1152 | 1153 | ``` 1154 | 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. 1155 | ``` 1156 | 1157 | 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`. 1158 | 1159 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
1160 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 1161 | 1162 | - [Configure the proxy yourself](#configuring-the-proxy-manually) 1163 | - Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 1164 | - Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 1165 | 1166 | ### "Invalid Host Header" Errors After Configuring Proxy 1167 | 1168 | 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). 1169 | 1170 | 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: 1171 | 1172 | > Invalid Host header 1173 | 1174 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 1175 | 1176 | ``` 1177 | HOST=mypublicdevhost.com 1178 | ``` 1179 | 1180 | If you restart the development server now and load the app from the specified host, it should work. 1181 | 1182 | 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:** 1183 | 1184 | ``` 1185 | # NOTE: THIS IS DANGEROUS! 1186 | # It exposes your machine to attacks from the websites you visit. 1187 | DANGEROUSLY_DISABLE_HOST_CHECK=true 1188 | ``` 1189 | 1190 | We don’t recommend this approach. 1191 | 1192 | ### Configuring the Proxy Manually 1193 | 1194 | > Note: this feature is available with `react-scripts@2.0.0` and higher. 1195 | 1196 | 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. 1197 | 1198 | 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`. 1199 | 1200 | First, install `http-proxy-middleware` using npm or Yarn: 1201 | 1202 | ```bash 1203 | $ npm install http-proxy-middleware --save 1204 | $ # or 1205 | $ yarn add http-proxy-middleware 1206 | ``` 1207 | 1208 | Next, create `src/setupProxy.js` and place the following contents in it: 1209 | 1210 | ```js 1211 | const proxy = require('http-proxy-middleware'); 1212 | 1213 | module.exports = function(app) { 1214 | // ... 1215 | }; 1216 | ``` 1217 | 1218 | You can now register proxies as you wish! Here's an example using the above `http-proxy-middleware`: 1219 | 1220 | ```js 1221 | const proxy = require('http-proxy-middleware'); 1222 | 1223 | module.exports = function(app) { 1224 | app.use(proxy('/api', { target: 'http://localhost:5000/' })); 1225 | }; 1226 | ``` 1227 | 1228 | > **Note:** You do not need to import this file anywhere. It is automatically registered when you start the development server. 1229 | 1230 | > **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). 1231 | 1232 | > **Note:** Passing the path to the proxy function allows you to use globbing and/or pattern matching on the path, which is more flexible than the express route matching. 1233 | 1234 | ## Using HTTPS in Development 1235 | 1236 | > Note: this feature is available with `react-scripts@0.4.0` and higher. 1237 | 1238 | 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. 1239 | 1240 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 1241 | 1242 | #### Windows (cmd.exe) 1243 | 1244 | ```cmd 1245 | set HTTPS=true&&npm start 1246 | ``` 1247 | 1248 | (Note: the lack of whitespace is intentional.) 1249 | 1250 | #### Windows (Powershell) 1251 | 1252 | ```Powershell 1253 | ($env:HTTPS = "true") -and (npm start) 1254 | ``` 1255 | 1256 | #### Linux, macOS (Bash) 1257 | 1258 | ```bash 1259 | HTTPS=true npm start 1260 | ``` 1261 | 1262 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1263 | 1264 | ## Generating Dynamic `` Tags on the Server 1265 | 1266 | 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: 1267 | 1268 | ```html 1269 | 1270 | 1271 | 1272 | 1273 | 1274 | ``` 1275 | 1276 | 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! 1277 | 1278 | 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. 1279 | 1280 | ## Pre-Rendering into Static HTML Files 1281 | 1282 | 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. 1283 | 1284 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1285 | 1286 | 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. 1287 | 1288 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1289 | 1290 | ## Injecting Data from the Server into the Page 1291 | 1292 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1293 | 1294 | ```js 1295 | 1296 | 1297 | 1298 | 1301 | ``` 1302 | 1303 | 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.** 1304 | 1305 | ## Running Tests 1306 | 1307 | > Note: this feature is available with `react-scripts@0.3.0` and higher.
1308 | 1309 | > [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) 1310 | 1311 | 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. 1312 | 1313 | 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. 1314 | 1315 | 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. 1316 | 1317 | 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. 1318 | 1319 | ### Filename Conventions 1320 | 1321 | Jest will look for test files with any of the following popular naming conventions: 1322 | 1323 | - Files with `.js` suffix in `__tests__` folders. 1324 | - Files with `.test.js` suffix. 1325 | - Files with `.spec.js` suffix. 1326 | 1327 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1328 | 1329 | 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. 1330 | 1331 | ### Command Line Interface 1332 | 1333 | 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. 1334 | 1335 | 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: 1336 | 1337 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1338 | 1339 | ### Version Control Integration 1340 | 1341 | 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. 1342 | 1343 | 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. 1344 | 1345 | 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. 1346 | 1347 | ### Writing Tests 1348 | 1349 | 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. 1350 | 1351 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1352 | 1353 | ```js 1354 | import sum from './sum'; 1355 | 1356 | it('sums numbers', () => { 1357 | expect(sum(1, 2)).toEqual(3); 1358 | expect(sum(2, 2)).toEqual(4); 1359 | }); 1360 | ``` 1361 | 1362 | All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
1363 | 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. 1364 | 1365 | ### Testing Components 1366 | 1367 | 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. 1368 | 1369 | 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: 1370 | 1371 | ```js 1372 | import React from 'react'; 1373 | import ReactDOM from 'react-dom'; 1374 | import App from './App'; 1375 | 1376 | it('renders without crashing', () => { 1377 | const div = document.createElement('div'); 1378 | ReactDOM.render(, div); 1379 | }); 1380 | ``` 1381 | 1382 | 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`. 1383 | 1384 | 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. 1385 | 1386 | 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: 1387 | 1388 | ```sh 1389 | npm install --save enzyme enzyme-adapter-react-16 react-test-renderer 1390 | ``` 1391 | 1392 | Alternatively you may use `yarn`: 1393 | 1394 | ```sh 1395 | yarn add enzyme enzyme-adapter-react-16 react-test-renderer 1396 | ``` 1397 | 1398 | 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.) 1399 | 1400 | The adapter will also need to be configured in your [global setup file](#initializing-test-environment): 1401 | 1402 | #### `src/setupTests.js` 1403 | 1404 | ```js 1405 | import { configure } from 'enzyme'; 1406 | import Adapter from 'enzyme-adapter-react-16'; 1407 | 1408 | configure({ adapter: new Adapter() }); 1409 | ``` 1410 | 1411 | > 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. 1412 | 1413 | Now you can write a smoke test with it: 1414 | 1415 | ```js 1416 | import React from 'react'; 1417 | import { shallow } from 'enzyme'; 1418 | import App from './App'; 1419 | 1420 | it('renders without crashing', () => { 1421 | shallow(); 1422 | }); 1423 | ``` 1424 | 1425 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `