├── .gitignore
├── README.md
├── finished.png
├── frontend.png
├── frontend
├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ └── registerServiceWorker.js
├── mvnw
├── mvnw.cmd
├── pom.xml
├── react-app.png
├── src
├── main
│ ├── java
│ │ └── no
│ │ │ └── kantega
│ │ │ └── springandreact
│ │ │ ├── HelloController.java
│ │ │ └── SpringAndReactApplication.java
│ └── resources
│ │ └── application.properties
└── test
│ └── java
│ └── no
│ └── kantega
│ └── springandreact
│ └── SpringAndReactApplicationTests.java
└── start-spring-io.png
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | *.iml
3 | target
4 |
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Webapp with Create React App and Spring Boot
2 | ===
3 |
4 | Developing Spring applications with Spring Boot is a real time saver. It gets you up and running quickly, and
5 | continues to make your life easier as you move to production and start releasing incremental updates to your
6 | application.
7 |
8 | Create React App does the same thing for your React frontend. It speeds up the initial phase by stitching together
9 | everything you need to get your React frontend working with minimal effort on your part, and it shortens your feedback
10 | loop by enabling hot reload. That way, you can just save your files, and changes will be immediately visible in
11 | the browser.
12 |
13 | This tutorial shows you how to combine Create React App with Spring Boot, giving you one single jar file to deploy.
14 |
15 | ## Goal:
16 | - Easily deploy to test and production environments
17 | - Frontend and backend in a single jar
18 | - Keep the benefits using the Create React App environment including:
19 | - Hot reload
20 | - Built in ES6 to ES5 transpiler
21 | - Optimized production build
22 |
23 | ## Getting started
24 | First, create a spring boot project with https://start.spring.io. Add the `Web` dependency. Set the groupId and
25 | artifactId to whatever you want. In this example we chose `no.kantega` and `spring-and-react`.
26 |
27 | 
28 |
29 | Generate the project and unzip it into your project directory. You probably want to initialize git, add a .gitignore
30 | and make your initial commit at this point.
31 |
32 | You should now have a project with a pom that looks something like this:
33 |
34 | ```xml
35 |
36 |
38 | 4.0.0
39 |
40 | no.kantega
41 | spring-and-react
42 | 0.0.1-SNAPSHOT
43 | jar
44 |
45 | spring-and-react
46 | Demo project for Spring Boot
47 |
48 |
49 | org.springframework.boot
50 | spring-boot-starter-parent
51 | 2.0.1.RELEASE
52 |
53 |
54 |
55 |
56 | UTF-8
57 | UTF-8
58 | 1.8
59 |
60 |
61 |
62 |
63 | org.springframework.boot
64 | spring-boot-starter-web
65 |
66 |
67 |
68 | org.springframework.boot
69 | spring-boot-starter-test
70 | test
71 |
72 |
73 |
74 |
75 |
76 |
77 | org.springframework.boot
78 | spring-boot-maven-plugin
79 |
80 |
81 |
82 |
83 | ```
84 |
85 | Right now, there are no services in this app, so if you were to run it and navigate to http://localhost:8080, you
86 | would only get a 404 page. So let's add a controller called `no.kantega.springandreact.HelloController`:
87 |
88 | ```java
89 | package no.kantega.springandreact;
90 |
91 | import org.springframework.web.bind.annotation.GetMapping;
92 | import org.springframework.web.bind.annotation.RestController;
93 |
94 | import java.util.Date;
95 |
96 | @RestController
97 | public class HelloController {
98 | @GetMapping("/api/hello")
99 | public String hello() {
100 | return "Hello, the time at the server is now " + new Date() + "\n";
101 | }
102 | }
103 | ```
104 |
105 | Now, let's run the application and try it out:
106 |
107 | In one command line window, start the application with
108 | ```
109 | $ mvn spring-boot:run
110 |
111 | [...]
112 | 2018-04-11 09:35:47.566 INFO 88567 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
113 | 2018-04-11 09:35:47.573 INFO 88567 --- [ main] n.k.s.SpringAndReactApplication : Started SpringAndReactApplication in 2.295 seconds (JVM running for 5.486)
114 | 2018-04-11 09:35:49.837 INFO 88567 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
115 | 2018-04-11 09:35:49.838 INFO 88567 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
116 | 2018-04-11 09:35:49.853 INFO 88567 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 15 ms
117 | ```
118 |
119 | Then, in another window, fetch http://localhost:8080/api/hello with curl or your web browser:
120 |
121 | ```
122 | $ curl http://localhost:8080/api/hello
123 | Hello, the time at the server is now Wed Apr 11 09:38:19 CEST 2018
124 | ```
125 |
126 | That's great, we now have a rest service in Spring Boot up and running!
127 |
128 | ## Adding React
129 |
130 | This section uses the tool [npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b),
131 | which is included with newer versions of `npm`.
132 |
133 | ```
134 | $ npx create-react-app frontend
135 |
136 | Creating a new React app in /Users/oven/git/react-and-spring/frontend.
137 |
138 | Installing packages. This might take a couple of minutes.
139 | Installing react, react-dom, and react-scripts...
140 | [...]
141 | Success! Created frontend at /Users/oven/git/react-and-spring/frontend
142 | [...]
143 | We suggest that you begin by typing:
144 |
145 | cd frontend
146 | npm start
147 | ```
148 |
149 | OK, let's do that, then :)
150 |
151 | ```
152 | $ cd frontend
153 | $ npm start
154 |
155 | [...]
156 |
157 | Compiled successfully!
158 |
159 | You can now view frontend in the browser.
160 |
161 | Local: http://localhost:3000/
162 | On Your Network: http://172.16.25.84:3000/
163 |
164 | Note that the development build is not optimized.
165 | To create a production build, use npm run build.
166 | ```
167 |
168 | This will open a web browser on your desktop, and it should display something like this:
169 |
170 | 
171 |
172 | ## Calling rest services in spring from React
173 | Now we have a backend server in Spring Boot running at http://localhost:8080 and a frontend in
174 | React running at http://localhost:3000. We'd like to be able to call services in the backend and
175 | display the results in the frontend. In order to do this (and not get into trouble with any
176 | cross-origin requests (CORS)) we ask the frontend server to proxy any requests from `:3000` to `:8080`.
177 |
178 | According to the
179 | [documentation](https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development#configuring-the-proxy-manually)
180 | you have to add a `proxy` entry to `frontend/package.json`. This will ensure that the web server at :3000 proxies
181 | any requests to `http://localhost:3000/api/*` to `http://localhost:8080/api`, which will enable us
182 | to call the backend without running into any CORS issues. Note that this is only useful during
183 | development. In a test or production environment, we will solve this in a different way. Read on :)
184 |
185 | `frontend/package.json`
186 | ```json
187 | {
188 | "name": "frontend",
189 | "version": "0.1.0",
190 | "private": true,
191 | "dependencies": {
192 | "react": "^16.12.0",
193 | "react-dom": "^16.12.0",
194 | "react-scripts": "^3.3.0"
195 | },
196 | "scripts": {
197 | "start": "react-scripts start",
198 | "build": "react-scripts build",
199 | "test": "react-scripts test --env=jsdom",
200 | "eject": "react-scripts eject"
201 | },
202 | "proxy": "http://localhost:8080",
203 | "browserslist": {
204 | "production": [
205 | ">0.2%",
206 | "not dead",
207 | "not op_mini all"
208 | ],
209 | "development": [
210 | "last 1 chrome version",
211 | "last 1 firefox version",
212 | "last 1 safari version"
213 | ]
214 | }
215 | }
216 |
217 | ```
218 |
219 | Make sure you have the backend running, and restart the frontend. You should now be able to fetch
220 | the hello service through the frontend server at http://localhost:3000/api/hello
221 |
222 | ```
223 | $ curl http://localhost:3000/api/hello
224 | Hello, the time at the server is now Wed Apr 11 10:04:47 CEST 2018
225 | ```
226 |
227 | Next, let's add a rest call to the frontend:
228 |
229 | Open `frontend/src/App.js` and replace its contents with this:
230 |
231 | ```javascript
232 | import React, {Component, useState, useEffect} from 'react';
233 | import logo from './logo.svg';
234 | import './App.css';
235 |
236 | function App () {
237 | const [message, setMessage] = useState("");
238 |
239 | useEffect(() => {
240 | fetch('/api/hello')
241 | .then(response => response.text())
242 | .then(message => {
243 | setMessage(message);
244 | });
245 | },[])
246 | return (
247 |
248 |
249 |
250 |
{message}
251 |
252 |
253 | To get started, edit src/App.js and save to reload.
254 |
255 |
256 | )
257 | }
258 |
259 | export default App;
260 | ```
261 |
262 | The frontend should now display the current time at the server:
263 |
264 | 
265 |
266 |
267 | Success! We now have a React frontend that talks to our Spring Boot backend. But how do we deploy
268 | this to production?
269 |
270 | ## Packaging the React app with Spring Boot
271 | We'd like to be able to publish *one* jar file to production, and that jar file should
272 | contain both the backend and the frontend. Spring Boot applications can serve static content if you put
273 | it into the `classes/public` directory of the application jar file. Create React App can build a
274 | static bundle for production by running `npm build` in the frontend directory.
275 |
276 | To accomplish this, we have to do the following:
277 |
278 | 1. create a production build of the frontend
279 | 2. copy the production build into `${target/classes/public}`
280 |
281 | We'll use `frontend-maven-plugin` in step 1, and `maven-antrun-plugin` in step 2. When we're done,
282 | we can just type `$ mvn clean install` and we'll end up with a single jar file containing both
283 | the frontend and the backend.
284 |
285 | ### Run npm from maven
286 | Add the following to `pom.xml` under `/build/plugins`:
287 | ```xml
288 |
289 | com.github.eirslett
290 | frontend-maven-plugin
291 | 1.6
292 |
293 | frontend
294 | target
295 |
296 |
297 |
298 | install node and npm
299 |
300 | install-node-and-npm
301 |
302 |
303 | v8.9.4
304 | 5.6.0
305 |
306 |
307 |
308 | npm install
309 |
310 | npm
311 |
312 |
313 | install
314 |
315 |
316 |
317 | npm run build
318 |
319 | npm
320 |
321 |
322 | run build
323 |
324 |
325 |
326 |
327 | ```
328 |
329 | When you run `mvn clean install`, maven will install npm and node locally and run `npm build`
330 | in the `frontend` directory.
331 |
332 | ```
333 | $ mvn clean install
334 | [...]
335 |
336 | [INFO] Installed node locally.
337 | [INFO] Installing npm version 5.6.0
338 | [INFO] Unpacking /Users/oven/.m2/repository/com/github/eirslett/npm/5.6.0/npm-5.6.0.tar.gz into /Users/oven/git/react-and-spring/target/node/node_modules
339 | [INFO] Installed npm locally.
340 | [INFO]
341 | [INFO] --- frontend-maven-plugin:1.6:npm (npm install) @ spring-and-react ---
342 | [INFO] Running 'npm install' in /Users/oven/git/react-and-spring/frontend
343 | [WARNING] npm WARN ajv-keywords@3.1.0 requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.
344 | [ERROR]
345 | [INFO] up to date in 7.23s
346 | [INFO]
347 | [INFO] --- frontend-maven-plugin:1.6:npm (npm run build) @ spring-and-react ---
348 | [INFO] Running 'npm run build' in /Users/oven/git/react-and-spring/frontend
349 | [INFO]
350 | [INFO] > frontend@0.1.0 build /Users/oven/git/react-and-spring/frontend
351 | [INFO] > react-scripts build
352 | [INFO]
353 | [INFO] Creating an optimized production build...
354 | [INFO] Compiled successfully.
355 | [...]
356 | ```
357 |
358 | This results in a production build of the frontend in `frontend/build`:
359 |
360 | ```
361 | $ tree frontend/build
362 | frontend/build
363 | ├── asset-manifest.json
364 | ├── favicon.ico
365 | ├── index.html
366 | ├── manifest.json
367 | ├── service-worker.js
368 | └── static
369 | ├── css
370 | │ ├── main.c17080f1.css
371 | │ └── main.c17080f1.css.map
372 | ├── js
373 | │ ├── main.9980f700.js
374 | │ └── main.9980f700.js.map
375 | └── media
376 | └── logo.5d5d9eef.svg
377 |
378 | 4 directories, 10 files
379 | ```
380 |
381 | ### Include frontend build files in spring boot jar
382 | We now have to copy these files to `target/classes/public` in order to serve them as static resources
383 | from the Spring Boot application. We'll use the ant plugin for this.
384 |
385 | Add the following to `pom.xml` under `/build/plugins`:
386 |
387 | ```xml
388 |
389 | maven-antrun-plugin
390 |
391 |
392 | generate-resources
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 | run
402 |
403 |
404 |
405 |
406 | ```
407 |
408 | This will ensure that the frontend build files are copied after they have been generated by `npm build`.
409 |
410 | Run maven again, and inspect the contents of the `target/classes` directory:
411 |
412 | ```
413 | $ mvn clean install
414 | [...]
415 |
416 | [INFO] --- maven-antrun-plugin:1.8:run (default) @ spring-and-react ---
417 | [INFO] Executing tasks
418 |
419 | main:
420 | [copy] Copying 10 files to /Users/oven/git/react-and-spring/target/classes/public
421 | [INFO] Executed tasks
422 |
423 | [...]
424 |
425 | $ tree target/classes
426 | target/classes
427 | ├── application.properties
428 | ├── no
429 | │ └── kantega
430 | │ └── springandreact
431 | │ ├── HelloController.class
432 | │ └── SpringAndReactApplication.class
433 | └── public
434 | ├── asset-manifest.json
435 | ├── favicon.ico
436 | ├── index.html
437 | ├── manifest.json
438 | ├── service-worker.js
439 | └── static
440 | ├── css
441 | │ ├── main.c17080f1.css
442 | │ └── main.c17080f1.css.map
443 | ├── js
444 | │ ├── main.9980f700.js
445 | │ └── main.9980f700.js.map
446 | └── media
447 | └── logo.5d5d9eef.svg
448 |
449 | 8 directories, 13 files
450 | ```
451 |
452 | You should also check that the files are present in the resulting jar file:
453 |
454 | ```
455 | $ jar tvf target/spring-and-react-0.0.1-SNAPSHOT.jar | grep public
456 | 0 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/
457 | 0 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/
458 | 0 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/css/
459 | 0 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/js/
460 | 0 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/media/
461 | 494612 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/js/main.9980f700.js.map
462 | 3235 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/service-worker.js
463 | 123322 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/js/main.9980f700.js
464 | 650 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/css/main.c17080f1.css
465 | 2671 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/media/logo.5d5d9eef.svg
466 | 1288 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/static/css/main.c17080f1.css.map
467 | 3870 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/favicon.ico
468 | 257 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/asset-manifest.json
469 | 548 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/index.html
470 | 317 Wed Apr 11 11:50:14 CEST 2018 BOOT-INF/classes/public/manifest.json
471 | ```
472 |
473 | Now, we're ready to start the application. Make sure you quit any running servers, and run the
474 | jar file
475 |
476 | ```
477 | $ java -jar target/spring-and-react-0.0.1-SNAPSHOT.jar
478 |
479 |
480 | . ____ _ __ _ _
481 | /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
482 | ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
483 | \\/ ___)| |_)| | | | | || (_| | ) ) ) )
484 | ' |____| .__|_| |_|_| |_\__, | / / / /
485 | =========|_|==============|___/=/_/_/_/
486 | :: Spring Boot :: (v2.0.1.RELEASE)
487 |
488 | 2018-04-11 11:53:44.983 INFO 93434 --- [ main] n.k.s.SpringAndReactApplication : Starting SpringAndReactApplication v0.0.1-SNAPSHOT on oven.local with PID 93434 (/Users/oven/git/react-and-spring/target/spring-and-react-0.0.1-SNAPSHOT.jar started by oven in /Users/oven/git/react-and-spring)
489 | 2018-04-11 11:53:44.986 INFO 93434 --- [ main] n.k.s.SpringAndReactApplication : No active profile set, falling back to default profiles: default
490 | 2018-04-11 11:53:45.045 INFO 93434 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5af3afd9: startup date [Wed Apr 11 11:53:45 CEST 2018]; root of context hierarchy
491 | 2018-04-11 11:53:46.180 INFO 93434 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
492 | 2018-04-11 11:53:46.221 INFO 93434 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
493 | 2018-04-11 11:53:46.222 INFO 93434 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
494 | [...]
495 | 2018-04-11 11:53:47.039 INFO 93434 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
496 | [...]
497 | ```
498 |
499 | Open your web browser, and navigate to http://localhost:8080. You should now see the following:
500 |
501 | 
502 |
503 | ## Congratulations!
504 |
505 | You now have a spring boot application with a React frontend. During development, you can now run the application
506 | using `React-scripts` by running `cd frontend; npm start`, and you'll have all the benefits of rapid application
507 | development with hot reloads and everything you might wish for, while being able to deploy the application to test
508 | and production environments as a single artifact.
509 |
510 | Happy hacking!
511 |
512 |
--------------------------------------------------------------------------------
/finished.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kantega/react-and-spring/4735ee6d081d7522dc6a91c65e87ba99ebc24cfd/finished.png
--------------------------------------------------------------------------------
/frontend.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kantega/react-and-spring/4735ee6d081d7522dc6a91c65e87ba99ebc24cfd/frontend.png
--------------------------------------------------------------------------------
/frontend/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/ignore-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 |
--------------------------------------------------------------------------------
/frontend/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/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/facebookincubator/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 and Polyfills](#supported-language-features-and-polyfills)
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 | - [Post-Processing CSS](#post-processing-css)
28 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
29 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
30 | - [Using the `public` Folder](#using-the-public-folder)
31 | - [Changing the HTML](#changing-the-html)
32 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
33 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
34 | - [Using Global Variables](#using-global-variables)
35 | - [Adding Bootstrap](#adding-bootstrap)
36 | - [Using a Custom Theme](#using-a-custom-theme)
37 | - [Adding Flow](#adding-flow)
38 | - [Adding a Router](#adding-a-router)
39 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
40 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
41 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
42 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
43 | - [Can I Use Decorators?](#can-i-use-decorators)
44 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests)
45 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
46 | - [Node](#node)
47 | - [Ruby on Rails](#ruby-on-rails)
48 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
49 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
50 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
51 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
52 | - [Using HTTPS in Development](#using-https-in-development)
53 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
54 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
55 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
56 | - [Running Tests](#running-tests)
57 | - [Filename Conventions](#filename-conventions)
58 | - [Command Line Interface](#command-line-interface)
59 | - [Version Control Integration](#version-control-integration)
60 | - [Writing Tests](#writing-tests)
61 | - [Testing Components](#testing-components)
62 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
63 | - [Initializing Test Environment](#initializing-test-environment)
64 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
65 | - [Coverage Reporting](#coverage-reporting)
66 | - [Continuous Integration](#continuous-integration)
67 | - [Disabling jsdom](#disabling-jsdom)
68 | - [Snapshot Testing](#snapshot-testing)
69 | - [Editor Integration](#editor-integration)
70 | - [Debugging Tests](#debugging-tests)
71 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome)
72 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code)
73 | - [Developing Components in Isolation](#developing-components-in-isolation)
74 | - [Getting Started with Storybook](#getting-started-with-storybook)
75 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
76 | - [Publishing Components to npm](#publishing-components-to-npm)
77 | - [Making a Progressive Web App](#making-a-progressive-web-app)
78 | - [Opting Out of Caching](#opting-out-of-caching)
79 | - [Offline-First Considerations](#offline-first-considerations)
80 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
81 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
82 | - [Deployment](#deployment)
83 | - [Static Server](#static-server)
84 | - [Other Solutions](#other-solutions)
85 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
86 | - [Building for Relative Paths](#building-for-relative-paths)
87 | - [Azure](#azure)
88 | - [Firebase](#firebase)
89 | - [GitHub Pages](#github-pages)
90 | - [Heroku](#heroku)
91 | - [Netlify](#netlify)
92 | - [Now](#now)
93 | - [S3 and CloudFront](#s3-and-cloudfront)
94 | - [Surge](#surge)
95 | - [Advanced Configuration](#advanced-configuration)
96 | - [Troubleshooting](#troubleshooting)
97 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
98 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
99 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
100 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
101 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
102 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
103 | - [Alternatives to Ejecting](#alternatives-to-ejecting)
104 | - [Something Missing?](#something-missing)
105 |
106 | ## Updating to New Releases
107 |
108 | Create React App is divided into two packages:
109 |
110 | * `create-react-app` is a global command-line utility that you use to create new projects.
111 | * `react-scripts` is a development dependency in the generated projects (including this one).
112 |
113 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
114 |
115 | 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.
116 |
117 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/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.
118 |
119 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
120 |
121 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
122 |
123 | ## Sending Feedback
124 |
125 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
126 |
127 | ## Folder Structure
128 |
129 | After creation, your project should look like this:
130 |
131 | ```
132 | my-app/
133 | README.md
134 | node_modules/
135 | package.json
136 | public/
137 | index.html
138 | favicon.ico
139 | src/
140 | App.css
141 | App.js
142 | App.test.js
143 | index.css
144 | index.js
145 | logo.svg
146 | ```
147 |
148 | For the project to build, **these files must exist with exact filenames**:
149 |
150 | * `public/index.html` is the page template;
151 | * `src/index.js` is the JavaScript entry point.
152 |
153 | You can delete or rename the other files.
154 |
155 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
156 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
157 |
158 | Only files inside `public` can be used from `public/index.html`.
159 | Read instructions below for using assets from JavaScript and HTML.
160 |
161 | You can, however, create more top-level directories.
162 | They will not be included in the production build so you can use them for things like documentation.
163 |
164 | ## Available Scripts
165 |
166 | In the project directory, you can run:
167 |
168 | ### `npm start`
169 |
170 | Runs the app in the development mode.
171 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
172 |
173 | The page will reload if you make edits.
174 | You will also see any lint errors in the console.
175 |
176 | ### `npm test`
177 |
178 | Launches the test runner in the interactive watch mode.
179 | See the section about [running tests](#running-tests) for more information.
180 |
181 | ### `npm run build`
182 |
183 | Builds the app for production to the `build` folder.
184 | It correctly bundles React in production mode and optimizes the build for the best performance.
185 |
186 | The build is minified and the filenames include the hashes.
187 | Your app is ready to be deployed!
188 |
189 | See the section about [deployment](#deployment) for more information.
190 |
191 | ### `npm run eject`
192 |
193 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
194 |
195 | 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.
196 |
197 | 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.
198 |
199 | 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.
200 |
201 | ## Supported Browsers
202 |
203 | By default, the generated project uses the latest version of React.
204 |
205 | You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers.
206 |
207 | ## Supported Language Features and Polyfills
208 |
209 | This project supports a superset of the latest JavaScript standard.
210 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
211 |
212 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
213 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
214 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
215 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
216 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
217 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
218 |
219 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
220 |
221 | 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.
222 |
223 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
224 |
225 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
226 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
227 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
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, or that the browsers you are targeting already support them.
230 |
231 | Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to.
232 |
233 | ## Syntax Highlighting in the Editor
234 |
235 | 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.
236 |
237 | ## Displaying Lint Output in the Editor
238 |
239 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
240 | >It also only works with npm 3 or higher.
241 |
242 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
243 |
244 | 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.
245 |
246 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
247 |
248 | ```js
249 | {
250 | "extends": "react-app"
251 | }
252 | ```
253 |
254 | Now your editor should report the linting warnings.
255 |
256 | 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.
257 |
258 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
259 |
260 | ## Debugging in the Editor
261 |
262 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
263 |
264 | 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.
265 |
266 | ### Visual Studio Code
267 |
268 | 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.
269 |
270 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
271 |
272 | ```json
273 | {
274 | "version": "0.2.0",
275 | "configurations": [{
276 | "name": "Chrome",
277 | "type": "chrome",
278 | "request": "launch",
279 | "url": "http://localhost:3000",
280 | "webRoot": "${workspaceRoot}/src",
281 | "sourceMapPathOverrides": {
282 | "webpack:///src/*": "${webRoot}/*"
283 | }
284 | }]
285 | }
286 | ```
287 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
288 |
289 | 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.
290 |
291 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting).
292 |
293 | ### WebStorm
294 |
295 | 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.
296 |
297 | 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.
298 |
299 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
300 |
301 | 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.
302 |
303 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
304 |
305 | ## Formatting Code Automatically
306 |
307 | 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/).
308 |
309 | To format our code whenever we make a commit in git, we need to install the following dependencies:
310 |
311 | ```sh
312 | npm install --save husky lint-staged prettier
313 | ```
314 |
315 | Alternatively you may use `yarn`:
316 |
317 | ```sh
318 | yarn add husky lint-staged prettier
319 | ```
320 |
321 | * `husky` makes it easy to use githooks as if they are npm scripts.
322 | * `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).
323 | * `prettier` is the JavaScript formatter we will run before commits.
324 |
325 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
326 |
327 | Add the following line to `scripts` section:
328 |
329 | ```diff
330 | "scripts": {
331 | + "precommit": "lint-staged",
332 | "start": "react-scripts start",
333 | "build": "react-scripts build",
334 | ```
335 |
336 | Next we add a 'lint-staged' field to the `package.json`, for example:
337 |
338 | ```diff
339 | "dependencies": {
340 | // ...
341 | },
342 | + "lint-staged": {
343 | + "src/**/*.{js,jsx,json,css}": [
344 | + "prettier --single-quote --write",
345 | + "git add"
346 | + ]
347 | + },
348 | "scripts": {
349 | ```
350 |
351 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx,json,css}"` to format your entire project for the first time.
352 |
353 | 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.
354 |
355 | ## Changing the Page ``
356 |
357 | 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.
358 |
359 | 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.
360 |
361 | 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.
362 |
363 | 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).
364 |
365 | ## Installing a Dependency
366 |
367 | 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`:
368 |
369 | ```sh
370 | npm install --save react-router
371 | ```
372 |
373 | Alternatively you may use `yarn`:
374 |
375 | ```sh
376 | yarn add react-router
377 | ```
378 |
379 | This works for any library, not just `react-router`.
380 |
381 | ## Importing a Component
382 |
383 | This project setup supports ES6 modules thanks to Babel.
384 | 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.
385 |
386 | For example:
387 |
388 | ### `Button.js`
389 |
390 | ```js
391 | import React, { Component } from 'react';
392 |
393 | class Button extends Component {
394 | render() {
395 | // ...
396 | }
397 | }
398 |
399 | export default Button; // Don’t forget to use export default!
400 | ```
401 |
402 | ### `DangerButton.js`
403 |
404 |
405 | ```js
406 | import React, { Component } from 'react';
407 | import Button from './Button'; // Import a component from another file
408 |
409 | class DangerButton extends Component {
410 | render() {
411 | return ;
412 | }
413 | }
414 |
415 | export default DangerButton;
416 | ```
417 |
418 | 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.
419 |
420 | 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'`.
421 |
422 | 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.
423 |
424 | Learn more about ES6 modules:
425 |
426 | * [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)
427 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
428 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
429 |
430 | ## Code Splitting
431 |
432 | 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.
433 |
434 | 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.
435 |
436 | Here is an example:
437 |
438 | ### `moduleA.js`
439 |
440 | ```js
441 | const moduleA = 'Hello';
442 |
443 | export { moduleA };
444 | ```
445 | ### `App.js`
446 |
447 | ```js
448 | import React, { Component } from 'react';
449 |
450 | class App extends Component {
451 | handleClick = () => {
452 | import('./moduleA')
453 | .then(({ moduleA }) => {
454 | // Use moduleA
455 | })
456 | .catch(err => {
457 | // Handle failure
458 | });
459 | };
460 |
461 | render() {
462 | return (
463 |
464 |
465 |
466 | );
467 | }
468 | }
469 |
470 | export default App;
471 | ```
472 |
473 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
474 |
475 | You can also use it with `async` / `await` syntax if you prefer it.
476 |
477 | ### With React Router
478 |
479 | 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).
480 |
481 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation.
482 |
483 | ## Adding a Stylesheet
484 |
485 | 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**:
486 |
487 | ### `Button.css`
488 |
489 | ```css
490 | .Button {
491 | padding: 20px;
492 | }
493 | ```
494 |
495 | ### `Button.js`
496 |
497 | ```js
498 | import React, { Component } from 'react';
499 | import './Button.css'; // Tell Webpack that Button.js uses these styles
500 |
501 | class Button extends Component {
502 | render() {
503 | // You can use them as regular CSS styles
504 | return ;
505 | }
506 | }
507 | ```
508 |
509 | **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-ui-engineering/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.
510 |
511 | 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.
512 |
513 | 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.
514 |
515 | ## Post-Processing CSS
516 |
517 | 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.
518 |
519 | For example, this:
520 |
521 | ```css
522 | .App {
523 | display: flex;
524 | flex-direction: row;
525 | align-items: center;
526 | }
527 | ```
528 |
529 | becomes this:
530 |
531 | ```css
532 | .App {
533 | display: -webkit-box;
534 | display: -ms-flexbox;
535 | display: flex;
536 | -webkit-box-orient: horizontal;
537 | -webkit-box-direction: normal;
538 | -ms-flex-direction: row;
539 | flex-direction: row;
540 | -webkit-box-align: center;
541 | -ms-flex-align: center;
542 | align-items: center;
543 | }
544 | ```
545 |
546 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
547 |
548 | ## Adding a CSS Preprocessor (Sass, Less etc.)
549 |
550 | 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 `` and `` components, we recommend creating a `