├── .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 | 
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 | 
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 | 
208 |
209 | Storybook should now launch in your web browser automatically.
210 |
211 | 
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 | 
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 | 
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 | 
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 | 
343 |
344 | Your `./dist/` directory should now contain the transpiled `index.js` file:
345 |
346 | ```shell
347 | $ tree -C ../dist
348 | ```
349 |
350 | 
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();
394 | const button = wrapper.find('.button');
395 | expect(button.length).toBe(1);
396 | })
397 |
398 | it('renders without props', function() {
399 | const wrapper = mount();
400 | const button = wrapper.find('.button');
401 | expect(button.length).toBe(1);
402 | })
403 |
404 | it('renders children when passed in', () => {
405 | const wrapper = mount(
406 |
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 |
419 | )
420 |
421 | wrapper.find('button').simulate('click')
422 |
423 | expect(onClick.mock.calls.length).toBe(1)
424 | })
425 | })
426 | ```
427 |
428 | > Note: we installed `babel-core@7.0.0-bridge.0` and `babel-jest` earlier to make Babel 7 code compatible with Jest. (See: [Install Common Dependencies](install-common-depenencies))
429 |
430 | Add the following "jest" section to your root `package.json`:
431 |
432 | ```json
433 | "jest": {
434 | "setupFiles": [
435 | "../../setupTests"
436 | ]
437 | }
438 | ```
439 |
440 | Your `packages/comp-button/package.json` should now look like this:
441 |
442 | ```json
443 | {
444 | "name": "@my-project/comp-button",
445 | "version": "0.1.0",
446 | "description": "A simple button component",
447 | "main": "dist/index.js",
448 | "module": "src/index.js",
449 | "scripts": {
450 | "transpile": "babel src -d dist --ignore '**/*.spec.js,**/*.stories.js'",
451 | "jest": "jest --coverage --verbose --color"
452 | },
453 | "babel": {
454 | "presets": [
455 | "@babel/preset-env",
456 | "@babel/preset-react"
457 | ],
458 | "env": {
459 | "test": {
460 | "plugins": [
461 | "transform-es2015-modules-commonjs"
462 | ]
463 | }
464 | }
465 | },
466 | "jest": {
467 | "setupFiles": [
468 | "../../setupTests"
469 | ]
470 | }
471 | }
472 | ```
473 |
474 | When Jest runs, `../../setupTests` file will reference `setupTests.js` in your Monorepo root.
475 |
476 | Let's add this `setupTests.js` file with some Enzyme helpers:
477 |
478 | ```js
479 | const enzyme = require('enzyme');
480 | const Adapter = require('enzyme-adapter-react-16');
481 | enzyme.configure({ adapter: new Adapter() });
482 | ```
483 |
484 | > Note: we deliberately use the older require syntax here, so that s`etupTests.js` is loadable without additional babel configuration.
485 |
486 | Now lets run Jest to see the spec working:
487 |
488 | ```shell
489 | lerna run jest
490 | ```
491 |
492 | > Note: We are using `jest` and not `test` to reserve the word "test" for running all tests, including End to End, linting, etc.
493 |
494 | 
495 |
496 |
497 | # Add a Story for Your React Component
498 |
499 | Now lets create a Storybook story for our new Button component:
500 |
501 | Add the following code to `index.stories.js`:
502 |
503 | ```jsx
504 | import React from 'react'
505 | import { storiesOf } from '@storybook/react'
506 | import { action } from '@storybook/addon-actions'
507 |
508 | import Button from '.'
509 |
510 | storiesOf('Button', module)
511 |
512 | .add('with text', () => (
513 |
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 | 
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 | 
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 |
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 | 
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 | 
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 | 
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 | 
766 |
767 | - **Storybook Hot Reloading**
768 |
769 | Nothing special here, but it's worth noting that our Storybook still hot-reloads too.
770 |
771 | 
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();
8 | const button = wrapper.find('.button');
9 | expect(button.length).toBe(1);
10 | })
11 |
12 | it('renders without props', function() {
13 | const wrapper = mount();
14 | const button = wrapper.find('.button');
15 | expect(button.length).toBe(1);
16 | })
17 |
18 | it('renders children when passed in', () => {
19 | const wrapper = mount(
20 |
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 |
33 | )
34 |
35 | wrapper.find('button').simulate('click')
36 |
37 | expect(onClick.mock.calls.length).toBe(1)
38 | })
39 | })
--------------------------------------------------------------------------------
/packages/comp-button/src/index.stories.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { storiesOf } from '@storybook/react'
3 | import { action } from '@storybook/addon-actions'
4 |
5 | import Button from '.'
6 |
7 | storiesOf('Button', module)
8 |
9 | .add('with text', () => (
10 |
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 `` 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.
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`.
162 | Read instructions below for using assets from JavaScript and HTML.
163 |
164 | You can, however, create more top-level directories.
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.
176 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
177 |
178 | The page will reload if you make edits.
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.
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.
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.
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.
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.
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.
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 ``
358 |
359 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` 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.
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 ;
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 |
466 |
467 |
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 ;
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 ;
554 | }
555 | }
556 | ```
557 |
558 | ### Result
559 |
560 | No clashes from other `.error` class names
561 |
562 | ```html
563 |
564 |