Produced by Araxis Merge on 9/25/2018 2:12:59 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.
# | Location | File | Last Modified |
---|---|---|---|
1 | build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\Java\src\main\dashboardapp | README.md | Thu Sep 6 11:37:12 2018 UTC |
2 | build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\Java\src\main\dashboardapp | README.md | Wed Sep 12 16:04:46 2018 UTC |
Description | Between Files 1 and 2 |
|
---|---|---|
Text Blocks | Lines | |
Unchanged | 2 | 4886 |
Changed | 1 | 2 |
Inserted | 0 | 0 |
Removed | 0 | 0 |
Whitespace | |
---|---|
Character case | Differences in character case are significant |
Line endings | Differences in line endings (CR and LF characters) are ignored |
CR/LF characters | Not shown in the comparison detail |
No regular expressions were active.
1 | This proje ct was boo tstrapped with [Crea te React A pp](https: //github.c om/faceboo kincubator /create-re act-app). | |
2 | ||
3 | Below you will find some infor mation on how to per form commo n tasks.<b r> | |
4 | You can fi nd the mos t recent v ersion of this guide [here](ht tps://gith ub.com/fac ebookincub ator/creat e-react-ap p/blob/mas ter/packag es/react-s cripts/tem plate/READ ME.md). | |
5 | ||
6 | ## Table o f Contents | |
7 | ||
8 | - [Updatin g to New R eleases](# updating-t o-new-rele ases) | |
9 | - [Sending Feedback] (#sending- feedback) | |
10 | - [Folder Structure] (#folder-s tructure) | |
11 | - [Availab le Scripts ](#availab le-scripts ) | |
12 | - [npm s tart](#npm -start) | |
13 | - [npm t est](#npm- test) | |
14 | - [npm r un build]( #npm-run-b uild) | |
15 | - [npm r un eject]( #npm-run-e ject) | |
16 | - [Support ed Browser s](#suppor ted-browse rs) | |
17 | - [Support ed Languag e Features and Polyf ills](#sup ported-lan guage-feat ures-and-p olyfills) | |
18 | - [Syntax Highlighti ng in the Editor](#s yntax-high lighting-i n-the-edit or) | |
19 | - [Display ing Lint O utput in t he Editor] (#displayi ng-lint-ou tput-in-th e-editor) | |
20 | - [Debuggi ng in the Editor](#d ebugging-i n-the-edit or) | |
21 | - [Formatt ing Code A utomatical ly](#forma tting-code -automatic ally) | |
22 | - [Changin g the Page `<title>` ](#changin g-the-page -title) | |
23 | - [Install ing a Depe ndency](#i nstalling- a-dependen cy) | |
24 | - [Importi ng a Compo nent](#imp orting-a-c omponent) | |
25 | - [Code Sp litting](# code-split ting) | |
26 | - [Adding a Styleshe et](#addin g-a-styles heet) | |
27 | - [Post-Pr ocessing C SS](#post- processing -css) | |
28 | - [Adding a CSS Prep rocessor ( Sass, Less etc.)](#a dding-a-cs s-preproce ssor-sass- less-etc) | |
29 | - [Adding Images, Fo nts, and F iles](#add ing-images -fonts-and -files) | |
30 | - [Using t he `public ` Folder]( #using-the -public-fo lder) | |
31 | - [Chang ing the HT ML](#chang ing-the-ht ml) | |
32 | - [Addin g Assets O utside of the Module System](# adding-ass ets-outsid e-of-the-m odule-syst em) | |
33 | - [When to Use the `public` Folder](#w hen-to-use -the-publi c-folder) | |
34 | - [Using G lobal Vari ables](#us ing-global -variables ) | |
35 | - [Adding Bootstrap] (#adding-b ootstrap) | |
36 | - [Using a Custom Theme](#us ing-a-cust om-theme) | |
37 | - [Adding Flow](#add ing-flow) | |
38 | - [Adding a Router]( #adding-a- router) | |
39 | - [Adding Custom Env ironment V ariables]( #adding-cu stom-envir onment-var iables) | |
40 | - [Refer encing Env ironment V ariables i n the HTML ](#referen cing-envir onment-var iables-in- the-html) | |
41 | - [Addin g Temporar y Environm ent Variab les In You r Shell](# adding-tem porary-env ironment-v ariables-i n-your-she ll) | |
42 | - [Addin g Developm ent Enviro nment Vari ables In ` .env`](#ad ding-devel opment-env ironment-v ariables-i n-env) | |
43 | - [Can I U se Decorat ors?](#can -i-use-dec orators) | |
44 | - [Fetchin g Data wit h AJAX Req uests](#fe tching-dat a-with-aja x-requests ) | |
45 | - [Integra ting with an API Bac kend](#int egrating-w ith-an-api -backend) | |
46 | - [Node] (#node) | |
47 | - [Ruby on Rails]( #ruby-on-r ails) | |
48 | - [Proxyin g API Requ ests in De velopment] (#proxying -api-reque sts-in-dev elopment) | |
49 | - ["Inva lid Host H eader" Err ors After Configurin g Proxy](# invalid-ho st-header- errors-aft er-configu ring-proxy ) | |
50 | - [Confi guring the Proxy Man ually](#co nfiguring- the-proxy- manually) | |
51 | - [Confi guring a W ebSocket P roxy](#con figuring-a -websocket -proxy) | |
52 | - [Using H TTPS in De velopment] (#using-ht tps-in-dev elopment) | |
53 | - [Generat ing Dynami c `<meta>` Tags on t he Server] (#generati ng-dynamic -meta-tags -on-the-se rver) | |
54 | - [Pre-Ren dering int o Static H TML Files] (#pre-rend ering-into -static-ht ml-files) | |
55 | - [Injecti ng Data fr om the Ser ver into t he Page](# injecting- data-from- the-server -into-the- page) | |
56 | - [Running Tests](#r unning-tes ts) | |
57 | - [Filen ame Conven tions](#fi lename-con ventions) | |
58 | - [Comma nd Line In terface](# command-li ne-interfa ce) | |
59 | - [Versi on Control Integrati on](#versi on-control -integrati on) | |
60 | - [Writi ng Tests]( #writing-t ests) | |
61 | - [Testi ng Compone nts](#test ing-compon ents) | |
62 | - [Using Third Par ty Asserti on Librari es](#using -third-par ty-asserti on-librari es) | |
63 | - [Initi alizing Te st Environ ment](#ini tializing- test-envir onment) | |
64 | - [Focus ing and Ex cluding Te sts](#focu sing-and-e xcluding-t ests) | |
65 | - [Cover age Report ing](#cove rage-repor ting) | |
66 | - [Conti nuous Inte gration](# continuous -integrati on) | |
67 | - [Disab ling jsdom ](#disabli ng-jsdom) | |
68 | - [Snaps hot Testin g](#snapsh ot-testing ) | |
69 | - [Edito r Integrat ion](#edit or-integra tion) | |
70 | - [Debuggi ng Tests]( #debugging -tests) | |
71 | - [Debug ging Tests in Chrome ](#debuggi ng-tests-i n-chrome) | |
72 | - [Debug ging Tests in Visual Studio Co de](#debug ging-tests -in-visual -studio-co de) | |
73 | - [Develop ing Compon ents in Is olation](# developing -component s-in-isola tion) | |
74 | - [Getti ng Started with Stor ybook](#ge tting-star ted-with-s torybook) | |
75 | - [Getti ng Started with Styl eguidist]( #getting-s tarted-wit h-stylegui dist) | |
76 | - [Publish ing Compon ents to np m](#publis hing-compo nents-to-n pm) | |
77 | - [Making a Progress ive Web Ap p](#making -a-progres sive-web-a pp) | |
78 | - [Optin g Out of C aching](#o pting-out- of-caching ) | |
79 | - [Offli ne-First C onsiderati ons](#offl ine-first- considerat ions) | |
80 | - [Progr essive Web App Metad ata](#prog ressive-we b-app-meta data) | |
81 | - [Analyzi ng the Bun dle Size]( #analyzing -the-bundl e-size) | |
82 | - [Deploym ent](#depl oyment) | |
83 | - [Stati c Server]( #static-se rver) | |
84 | - [Other Solutions ](#other-s olutions) | |
85 | - [Servi ng Apps wi th Client- Side Routi ng](#servi ng-apps-wi th-client- side-routi ng) | |
86 | - [Build ing for Re lative Pat hs](#build ing-for-re lative-pat hs) | |
87 | - [Azure ](#azure) | |
88 | - [Fireb ase](#fire base) | |
89 | - [GitHu b Pages](# github-pag es) | |
90 | - [Herok u](#heroku ) | |
91 | - [Netli fy](#netli fy) | |
92 | - [Now]( #now) | |
93 | - [S3 an d CloudFro nt](#s3-an d-cloudfro nt) | |
94 | - [Surge ](#surge) | |
95 | - [Advance d Configur ation](#ad vanced-con figuration ) | |
96 | - [Trouble shooting]( #troublesh ooting) | |
97 | - [`npm start` doe sn’t det ect change s](#npm-st art-doesnt -detect-ch anges) | |
98 | - [`npm test` hang s on macOS Sierra](# npm-test-h angs-on-ma cos-sierra ) | |
99 | - [`npm run build` exits too early](#n pm-run-bui ld-exits-t oo-early) | |
100 | - [`npm run build` fails on Heroku](#n pm-run-bui ld-fails-o n-heroku) | |
101 | - [`npm run build` fails to minify](#n pm-run-bui ld-fails-t o-minify) | |
102 | - [Momen t.js local es are mis sing](#mom entjs-loca les-are-mi ssing) | |
103 | - [Alterna tives to E jecting](# alternativ es-to-ejec ting) | |
104 | - [Somethi ng Missing ?](#someth ing-missin g) | |
105 | ||
106 | ## Updatin g to New R eleases | |
107 | ||
108 | Create Rea ct App is divided in to two pac kages: | |
109 | ||
110 | * `create- react-app` is a glob al command -line util ity that y ou use to create new projects. | |
111 | * `react-s cripts` is a develop ment depen dency in t he generat ed project s (includi ng this on e). | |
112 | ||
113 | You almost never nee d to updat e `create- react-app` itself: i t delegate s all the setup to ` react-scri pts`. | |
114 | ||
115 | When you r un `create -react-app `, it alwa ys creates the proje ct with th e latest v ersion of `react-scr ipts` so y ou’ll ge t all the new featur es and imp rovements in newly c reated app s automati cally. | |
116 | ||
117 | To update an existin g project to a new v ersion of `react-scr ipts`, [op en the cha ngelog](ht tps://gith ub.com/fac ebookincub ator/creat e-react-ap p/blob/mas ter/CHANGE LOG.md), f ind the ve rsion youâ €™re curre ntly on (c heck `pack age.json` in this fo lder if yo u’re not sure), an d apply th e migratio n instruct ions for t he newer v ersions. | |
118 | ||
119 | In most ca ses bumpin g the `rea ct-scripts ` version in `packag e.json` an d running `npm insta ll` in thi s folder s hould be e nough, but it’s go od to cons ult the [c hangelog]( https://gi thub.com/f acebookinc ubator/cre ate-react- app/blob/m aster/CHAN GELOG.md) for potent ial breaki ng changes . | |
120 | ||
121 | We commit to keeping the break ing change s minimal so you can upgrade ` react-scri pts` painl essly. | |
122 | ||
123 | ## Sending Feedback | |
124 | ||
125 | We are alw ays open t o [your fe edback](ht tps://gith ub.com/fac ebookincub ator/creat e-react-ap p/issues). | |
126 | ||
127 | ## Folder Structure | |
128 | ||
129 | After crea tion, your project s hould look like this : | |
130 | ||
131 | ``` | |
132 | my-app/ | |
133 | README.m d | |
134 | node_mod ules/ | |
135 | package. json | |
136 | public/ | |
137 | index. html | |
138 | favico n.ico | |
139 | src/ | |
140 | App.cs s | |
141 | App.js | |
142 | App.te st.js | |
143 | index. css | |
144 | index. js | |
145 | logo.s vg | |
146 | ``` | |
147 | ||
148 | For the pr oject to b uild, **th ese files must exist with exac t filename s**: | |
149 | ||
150 | * `public/ index.html ` is the p age templa te; | |
151 | * `src/ind ex.js` is the JavaSc ript entry point. | |
152 | ||
153 | You can de lete or re name the o ther files . | |
154 | ||
155 | You may cr eate subdi rectories inside `sr c`. For fa ster rebui lds, only files insi de `src` a re process ed by Webp ack.<br> | |
156 | You need t o **put an y JS and C SS files i nside `src `**, other wise Webpa ck won’t see them. | |
157 | ||
158 | Only files inside `p ublic` can be used f rom `publi c/index.ht ml`.<br> | |
159 | Read instr uctions be low for us ing assets from Java Script and HTML. | |
160 | ||
161 | You can, h owever, cr eate more top-level directorie s.<br> | |
162 | They will not be inc luded in t he product ion build so you can use them for things like docu mentation. | |
163 | ||
164 | ## Availab le Scripts | |
165 | ||
166 | In the pro ject direc tory, you can run: | |
167 | ||
168 | ### `npm s tart` | |
169 | ||
170 | Runs the a pp in the developmen t mode.<br > | |
171 | Open [http ://localho st:3000](h ttp://loca lhost:3000 ) to view it in the browser. | |
172 | ||
173 | The page w ill reload if you ma ke edits.< br> | |
174 | You will a lso see an y lint err ors in the console. | |
175 | ||
176 | ### `npm t est` | |
177 | ||
178 | Launches t he test ru nner in th e interact ive watch mode.<br> | |
179 | See the se ction abou t [running tests](#r unning-tes ts) for mo re informa tion. | |
180 | ||
181 | ### `npm r un build` | |
182 | ||
183 | Builds the app for p roduction to the `bu ild` folde r.<br> | |
184 | It correct ly bundles React in production mode and optimizes the build for the be st perform ance. | |
185 | ||
186 | The build is minifie d and the filenames include th e hashes.< br> | |
187 | Your app i s ready to be deploy ed! | |
188 | ||
189 | See the se ction abou t [deploym ent](#depl oyment) fo r more inf ormation. | |
190 | ||
191 | ### `npm r un eject` | |
192 | ||
193 | **Note: th is is a on e-way oper ation. Onc e you `eje ct`, you c an’t go back!** | |
194 | ||
195 | If you are n’t sati sfied with the build tool and configurat ion choice s, you can `eject` a t any time . This com mand will remove the single bu ild depend ency from your proje ct. | |
196 | ||
197 | Instead, i t will cop y all the configurat ion files and the tr ansitive d ependencie s (Webpack , Babel, E SLint, etc ) right in to your pr oject so y ou have fu ll control over them . All of t he command s except ` eject` wil l still wo rk, but th ey will po int to the copied sc ripts so y ou can twe ak them. A t this poi nt you’r e on your own. | |
198 | ||
199 | You don’ t have to ever use ` eject`. Th e curated feature se t is suita ble for sm all and mi ddle deplo yments, an d you shou ldn’t fe el obligat ed to use this featu re. Howeve r we under stand that this tool wouldn’ t be usefu l if you c ouldn’t customize it when yo u are read y for it. | |
200 | ||
201 | ## Support ed Browser s | |
202 | ||
203 | By default , the gene rated proj ect uses t he latest version of React. | |
204 | ||
205 | You can re fer [to th e React do cumentatio n](https:/ /reactjs.o rg/docs/re act-dom.ht ml#browser -support) for more i nformation about sup ported bro wsers. | |
206 | ||
207 | ## Support ed Languag e Features and Polyf ills | |
208 | ||
209 | This proje ct support s a supers et of the latest Jav aScript st andard.<br > | |
210 | In additio n to [ES6] (https://g ithub.com/ lukehoban/ es6feature s) syntax features, it also su pports: | |
211 | ||
212 | * [Exponen tiation Op erator](ht tps://gith ub.com/rwa ldron/expo nentiation -operator) (ES2016). | |
213 | * [Async/a wait](http s://github .com/tc39/ ecmascript -asyncawai t) (ES2017 ). | |
214 | * [Object Rest/Sprea d Properti es](https: //github.c om/sebmark bage/ecmas cript-rest -spread) ( stage 3 pr oposal). | |
215 | * [Dynamic import()] (https://g ithub.com/ tc39/propo sal-dynami c-import) (stage 3 p roposal) | |
216 | * [Class F ields and Static Pro perties](h ttps://git hub.com/tc 39/proposa l-class-pu blic-field s) (part o f stage 3 proposal). | |
217 | * [JSX](ht tps://face book.githu b.io/react /docs/intr oducing-js x.html) an d [Flow](h ttps://flo wtype.org/ ) syntax. | |
218 | ||
219 | Learn more about [di fferent pr oposal sta ges](https ://babeljs .io/docs/p lugins/#pr esets-stag e-x-experi mental-pre sets-). | |
220 | ||
221 | While we r ecommend u sing exper imental pr oposals wi th some ca ution, Fac ebook heav ily uses t hese featu res in the product c ode, so we intend to provide [ codemods]( https://me dium.com/@ cpojer/eff ective-jav ascript-co demods-5a6 686bb46fb) if any of these pro posals cha nge in the future. | |
222 | ||
223 | Note that **the proj ect only i ncludes a few ES6 [p olyfills]( https://en .wikipedia .org/wiki/ Polyfill)* *: | |
224 | ||
225 | * [`Object .assign()` ](https:// developer. mozilla.or g/en/docs/ Web/JavaSc ript/Refer ence/Globa l_Objects/ Object/ass ign) via [ `object-as sign`](htt ps://githu b.com/sind resorhus/o bject-assi gn). | |
226 | * [`Promis e`](https: //develope r.mozilla. org/en-US/ docs/Web/J avaScript/ Reference/ Global_Obj ects/Promi se) via [` promise`]( https://gi thub.com/t hen/promis e). | |
227 | * [`fetch( )`](https: //develope r.mozilla. org/en/doc s/Web/API/ Fetch_API) via [`wha twg-fetch` ](https:// github.com /github/fe tch). | |
228 | ||
229 | If you use any other ES6+ feat ures that need **run time suppo rt** (such as `Array .from()` o r `Symbol` ), make su re you are including the appro priate pol yfills man ually, or that the b rowsers yo u are targ eting alre ady suppor t them. | |
230 | ||
231 | Also note that using some newe r syntax f eatures li ke `for... of` or `[. ..nonArray Value]` ca uses Babel to emit c ode that d epends on ES6 runtim e features and might not work without a polyfill. When in do ubt, use [ Babel REPL ](https:// babeljs.io /repl/) to see what any specif ic syntax compiles d own to. | |
232 | ||
233 | ## Syntax Highlighti ng in the Editor | |
234 | ||
235 | To configu re the syn tax highli ghting in your favor ite text e ditor, hea d to the [ relevant B abel docum entation p age](https ://babeljs .io/docs/e ditors) an d follow t he instruc tions. Som e of the m ost popula r editors are covere d. | |
236 | ||
237 | ## Display ing Lint O utput in t he Editor | |
238 | ||
239 | >Note: thi s feature is availab le with `r eact-scrip ts@0.2.0` and higher .<br> | |
240 | >It also o nly works with npm 3 or higher . | |
241 | ||
242 | Some edito rs, includ ing Sublim e Text, At om, and Vi sual Studi o Code, pr ovide plug ins for ES Lint. | |
243 | ||
244 | They are n ot require d for lint ing. You s hould see the linter output ri ght in you r terminal as well a s the brow ser consol e. However , if you p refer the lint resul ts to appe ar right i n your edi tor, there are some extra step s you can do. | |
245 | ||
246 | You would need to in stall an E SLint plug in for you r editor f irst. Then , add a fi le called `.eslintrc ` to the p roject roo t: | |
247 | ||
248 | ```js | |
249 | { | |
250 | "extends ": "react- app" | |
251 | } | |
252 | ``` | |
253 | ||
254 | Now your e ditor shou ld report the lintin g warnings . | |
255 | ||
256 | Note that even if yo u edit you r `.eslint rc` file f urther, th ese change s will **o nly affect the edito r integrat ion**. The y won’t affect the terminal and in-bro wser lint output. Th is is beca use Create React App intention ally provi des a mini mal set of rules tha t find com mon mistak es. | |
257 | ||
258 | If you wan t to enfor ce a codin g style fo r your pro ject, cons ider using [Prettier ](https:// github.com /jlongster /prettier) instead o f ESLint s tyle rules . | |
259 | ||
260 | ## Debuggi ng in the Editor | |
261 | ||
262 | **This fea ture is cu rrently on ly support ed by [Vis ual Studio Code](htt ps://code. visualstud io.com) an d [WebStor m](https:/ /www.jetbr ains.com/w ebstorm/). ** | |
263 | ||
264 | Visual Stu dio Code a nd WebStor m support debugging out of the box with Create Rea ct App. Th is enables you as a developer to write a nd debug y our React code witho ut leaving the edito r, and mos t importan tly it ena bles you t o have a c ontinuous developmen t workflow , where co ntext swit ching is m inimal, as you don†™t have to switch be tween tool s. | |
265 | ||
266 | ### Visual Studio Co de | |
267 | ||
268 | You would need to ha ve the lat est versio n of [VS C ode](https ://code.vi sualstudio .com) and VS Code [C hrome Debu gger Exten sion](http s://market place.visu alstudio.c om/items?i temName=ms jsdiag.deb ugger-for- chrome) in stalled. | |
269 | ||
270 | Then add t he block b elow to yo ur `launch .json` fil e and put it inside the `.vsco de` folder in your a pp’s roo t director y. | |
271 | ||
272 | ```json | |
273 | { | |
274 | "version ": "0.2.0" , | |
275 | "configu rations": [{ | |
276 | "name" : "Chrome" , | |
277 | "type" : "chrome" , | |
278 | "reque st": "laun ch", | |
279 | "url": "http://l ocalhost:3 000", | |
280 | "webRo ot": "${wo rkspaceRoo t}/src", | |
281 | "sourc eMapPathOv errides": { | |
282 | "web pack:///sr c/*": "${w ebRoot}/*" | |
283 | } | |
284 | }] | |
285 | } | |
286 | ``` | |
287 | >Note: the URL may b e differen t if you'v e made adj ustments v ia the [HO ST or PORT environme nt variabl es](#advan ced-config uration). | |
288 | ||
289 | Start your app by ru nning `npm start`, a nd start d ebugging i n VS Code by pressin g `F5` or by clickin g the gree n debug ic on. You ca n now writ e code, se t breakpoi nts, make changes to the code, and debug your newl y modified code—al l from you r editor. | |
290 | ||
291 | Having pro blems with VS Code D ebugging? Please see their [tr oubleshoot ing guide] (https://g ithub.com/ Microsoft/ vscode-chr ome-debug/ blob/maste r/README.m d#troubles hooting). | |
292 | ||
293 | ### WebSto rm | |
294 | ||
295 | You would need to ha ve [WebSto rm](https: //www.jetb rains.com/ webstorm/) and [JetB rains IDE Support](h ttps://chr ome.google .com/webst ore/detail /jetbrains -ide-suppo rt/hmhgedd bohgjknpmj agkdomcpob mllji) Chr ome extens ion instal led. | |
296 | ||
297 | In the Web Storm menu `Run` sel ect `Edit Configurat ions...`. Then click `+` and s elect `Jav aScript De bug`. Past e `http:// localhost: 3000` into the URL f ield and s ave the co nfiguratio n. | |
298 | ||
299 | >Note: the URL may b e differen t if you'v e made adj ustments v ia the [HO ST or PORT environme nt variabl es](#advan ced-config uration). | |
300 | ||
301 | Start your app by ru nning `npm start`, t hen press `^D` on ma cOS or `F9 ` on Windo ws and Lin ux or clic k the gree n debug ic on to star t debuggin g in WebSt orm. | |
302 | ||
303 | The same w ay you can debug you r applicat ion in Int elliJ IDEA Ultimate, PhpStorm, PyCharm P ro, and Ru byMine. | |
304 | ||
305 | ## Formatt ing Code A utomatical ly | |
306 | ||
307 | Prettier i s an opini onated cod e formatte r with sup port for J avaScript, CSS and J SON. With Prettier y ou can for mat the co de you wri te automat ically to ensure a c ode style within you r project. See the [ Prettier's GitHub pa ge](https: //github.c om/prettie r/prettier ) for more informati on, and lo ok at this [page to see it in action](ht tps://pret tier.githu b.io/prett ier/). | |
308 | ||
309 | To format our code w henever we make a co mmit in gi t, we need to instal l the foll owing depe ndencies: | |
310 | ||
311 | ```sh | |
312 | npm instal l --save h usky lint- staged pre ttier | |
313 | ``` | |
314 | ||
315 | Alternativ ely you ma y use `yar n`: | |
316 | ||
317 | ```sh | |
318 | yarn add h usky lint- staged pre ttier | |
319 | ``` | |
320 | ||
321 | * `husky` makes it e asy to use githooks as if they are npm s cripts. | |
322 | * `lint-st aged` allo ws us to r un scripts on staged files in git. See t his [blog post about lint-stag ed to lear n more abo ut it](htt ps://mediu m.com/@oko netchnikov /make-lint ing-great- again-f389 0e1ad6b8). | |
323 | * `prettie r` is the JavaScript formatter we will r un before commits. | |
324 | ||
325 | Now we can make sure every fil e is forma tted corre ctly by ad ding a few lines to the `packa ge.json` i n the proj ect root. | |
326 | ||
327 | Add the fo llowing li ne to `scr ipts` sect ion: | |
328 | ||
329 | ```diff | |
330 | "scripts ": { | |
331 | + "preco mmit": "li nt-staged" , | |
332 | "start ": "react- scripts st art", | |
333 | "build ": "react- scripts bu ild", | |
334 | ``` | |
335 | ||
336 | Next we ad d a 'lint- staged' fi eld to the `package. json`, for example: | |
337 | ||
338 | ```diff | |
339 | "depende ncies": { | |
340 | // ... | |
341 | }, | |
342 | + "lint-st aged": { | |
343 | + "src/* */*.{js,js x,json,css }": [ | |
344 | + "pre ttier --si ngle-quote --write", | |
345 | + "git add" | |
346 | + ] | |
347 | + }, | |
348 | "scripts ": { | |
349 | ``` | |
350 | ||
351 | Now, whene ver you ma ke a commi t, Prettie r will for mat the ch anged file s automati cally. You can also run `./nod e_modules/ .bin/prett ier --sing le-quote - -write "sr c/**/*.{js ,jsx,json, css}"` to format you r entire p roject for the first time. | |
352 | ||
353 | Next you m ight want to integra te Prettie r in your favorite e ditor. Rea d the sect ion on [Ed itor Integ ration](ht tps://pret tier.io/do cs/en/edit ors.html) on the Pre ttier GitH ub page. | |
354 | ||
355 | ## Changin g the Page `<title>` | |
356 | ||
357 | You can fi nd the sou rce HTML f ile in the `public` folder of the genera ted projec t. You may edit the `<title>` tag in it to change the title from “Re act App†to anythi ng else. | |
358 | ||
359 | Note that normally y ou wouldnâ €™t edit f iles in th e `public` folder ve ry often. For exampl e, [adding a stylesh eet](#addi ng-a-style sheet) is done witho ut touchin g the HTML . | |
360 | ||
361 | If you nee d to dynam ically upd ate the pa ge title b ased on th e content, you can u se the bro wser [`doc ument.titl e`](https: //develope r.mozilla. org/en-US/ docs/Web/A PI/Documen t/title) A PI. For mo re complex scenarios when you want to ch ange the t itle from React comp onents, yo u can use [React Hel met](https ://github. com/nfl/re act-helmet ), a third party lib rary. | |
362 | ||
363 | If you use a custom server for your app in product ion and wa nt to modi fy the tit le before it gets se nt to the browser, y ou can fol low advice in [this section](# generating -dynamic-m eta-tags-o n-the-serv er). Alter natively, you can pr e-build ea ch page as a static HTML file which then loads the JavaScrip t bundle, which is c overed [he re](#pre-r endering-i nto-static -html-file s). | |
364 | ||
365 | ## Install ing a Depe ndency | |
366 | ||
367 | The genera ted projec t includes React and ReactDOM as depende ncies. It also inclu des a set of scripts used by C reate Reac t App as a developme nt depende ncy. You m ay install other dep endencies (for examp le, React Router) wi th `npm`: | |
368 | ||
369 | ```sh | |
370 | npm instal l --save r eact-route r | |
371 | ``` | |
372 | ||
373 | Alternativ ely you ma y use `yar n`: | |
374 | ||
375 | ```sh | |
376 | yarn add r eact-route r | |
377 | ``` | |
378 | ||
379 | This works for any l ibrary, no t just `re act-router `. | |
380 | ||
381 | ## Importi ng a Compo nent | |
382 | ||
383 | This proje ct setup s upports ES 6 modules thanks to Babel.<br> | |
384 | While you can still use `requi re()` and `module.ex ports`, we encourage you to us e [`import ` and `exp ort`](http ://explori ngjs.com/e s6/ch_modu les.html) instead. | |
385 | ||
386 | For exampl e: | |
387 | ||
388 | ### `Butto n.js` | |
389 | ||
390 | ```js | |
391 | import Rea ct, { Comp onent } fr om 'react' ; | |
392 | ||
393 | class Butt on extends Component { | |
394 | render() { | |
395 | // ... | |
396 | } | |
397 | } | |
398 | ||
399 | export def ault Butto n; // Donâ €™t forget to use ex port defau lt! | |
400 | ``` | |
401 | ||
402 | ### `Dange rButton.js ` | |
403 | ||
404 | ||
405 | ```js | |
406 | import Rea ct, { Comp onent } fr om 'react' ; | |
407 | import But ton from ' ./Button'; // Import a compone nt from an other file | |
408 | ||
409 | class Dang erButton e xtends Com ponent { | |
410 | render() { | |
411 | return <Button c olor="red" />; | |
412 | } | |
413 | } | |
414 | ||
415 | export def ault Dange rButton; | |
416 | ``` | |
417 | ||
418 | Be aware o f the [dif ference be tween defa ult and na med export s](http:// stackoverf low.com/qu estions/36 795819/rea ct-native- es-6-when- should-i-u se-curly-b races-for- import/367 96281#3679 6281). It is a commo n source o f mistakes . | |
419 | ||
420 | We suggest that you stick to u sing defau lt imports and expor ts when a module onl y exports a single t hing (for example, a component ). That’ s what you get when you use `e xport defa ult Button ` and `imp ort Button from './B utton'`. | |
421 | ||
422 | Named expo rts are us eful for u tility mod ules that export sev eral funct ions. A mo dule may h ave at mos t one defa ult export and as ma ny named e xports as you like. | |
423 | ||
424 | Learn more about ES6 modules: | |
425 | ||
426 | * [When to use the c urly brace s?](http:/ /stackover flow.com/q uestions/3 6795819/re act-native -es-6-when -should-i- use-curly- braces-for -import/36 796281#367 96281) | |
427 | * [Explori ng ES6: Mo dules](htt p://explor ingjs.com/ es6/ch_mod ules.html) | |
428 | * [Underst anding ES6 : Modules] (https://l eanpub.com /understan dinges6/re ad#leanpub -auto-enca psulating- code-with- modules) | |
429 | ||
430 | ## Code Sp litting | |
431 | ||
432 | Instead of downloadi ng the ent ire app be fore users can use i t, code sp litting al lows you t o split yo ur code in to small c hunks whic h you can then load on demand. | |
433 | ||
434 | This proje ct setup s upports co de splitti ng via [dy namic `imp ort()`](ht tp://2alit y.com/2017 /01/import -operator. html#loadi ng-code-on -demand). Its [propo sal](https ://github. com/tc39/p roposal-dy namic-impo rt) is in stage 3. T he `import ()` functi on-like fo rm takes t he module name as an argument and return s a [`Prom ise`](http s://develo per.mozill a.org/en-U S/docs/Web /JavaScrip t/Referenc e/Global_O bjects/Pro mise) whic h always r esolves to the names pace objec t of the m odule. | |
435 | ||
436 | Here is an example: | |
437 | ||
438 | ### `modul eA.js` | |
439 | ||
440 | ```js | |
441 | const modu leA = 'Hel lo'; | |
442 | ||
443 | export { m oduleA }; | |
444 | ``` | |
445 | ### `App.j s` | |
446 | ||
447 | ```js | |
448 | import Rea ct, { Comp onent } fr om 'react' ; | |
449 | ||
450 | class App extends Co mponent { | |
451 | handleCl ick = () = > { | |
452 | import ('./module A') | |
453 | .the n(({ modul eA }) => { | |
454 | // Use modul eA | |
455 | }) | |
456 | .cat ch(err => { | |
457 | // Handle fa ilure | |
458 | }); | |
459 | }; | |
460 | ||
461 | render() { | |
462 | return ( | |
463 | <div > | |
464 | <b utton onCl ick={this. handleClic k}>Load</b utton> | |
465 | </di v> | |
466 | ); | |
467 | } | |
468 | } | |
469 | ||
470 | export def ault App; | |
471 | ``` | |
472 | ||
473 | This will make `modu leA.js` an d all its unique dep endencies as a separ ate chunk that only loads afte r the user clicks th e 'Load' b utton. | |
474 | ||
475 | You can al so use it with `asyn c` / `awai t` syntax if you pre fer it. | |
476 | ||
477 | ### With R eact Route r | |
478 | ||
479 | If you are using Rea ct Router check out [this tuto rial](http ://serverl ess-stack. com/chapte rs/code-sp litting-in -create-re act-app.ht ml) on how to use co de splitti ng with it . You can find the c ompanion G itHub repo sitory [he re](https: //github.c om/Anomaly Innovation s/serverle ss-stack-d emo-client /tree/code -splitting -in-create -react-app ). | |
480 | ||
481 | Also check out the [ Code Split ting](http s://reactj s.org/docs /code-spli tting.html ) section in React d ocumentati on. | |
482 | ||
483 | ## Adding a Styleshe et | |
484 | ||
485 | This proje ct setup u ses [Webpa ck](https: //webpack. js.org/) f or handlin g all asse ts. Webpac k offers a custom wa y of “ex tending†the conce pt of `imp ort` beyon d JavaScri pt. To exp ress that a JavaScri pt file de pends on a CSS file, you need to **impor t the CSS from the J avaScript file**: | |
486 | ||
487 | ### `Butto n.css` | |
488 | ||
489 | ```css | |
490 | .Button { | |
491 | padding: 20px; | |
492 | } | |
493 | ``` | |
494 | ||
495 | ### `Butto n.js` | |
496 | ||
497 | ```js | |
498 | import Rea ct, { Comp onent } fr om 'react' ; | |
499 | import './ Button.css '; // Tell Webpack t hat Button .js uses t hese style s | |
500 | ||
501 | class Butt on extends Component { | |
502 | render() { | |
503 | // You can use t hem as reg ular CSS s tyles | |
504 | return <div clas sName="But ton" />; | |
505 | } | |
506 | } | |
507 | ``` | |
508 | ||
509 | **This is not requir ed for Rea ct** but m any people find this feature c onvenient. You can r ead about the benefi ts of this approach [here](htt ps://mediu m.com/seek -ui-engine ering/bloc k-element- modifying- your-javas cript-comp onents-d7f 99fcab52b) . However you should be aware that this makes your code less portable to other b uild tools and envir onments th an Webpack . | |
510 | ||
511 | In develop ment, expr essing dep endencies this way a llows your styles to be reload ed on the fly as you edit them . In produ ction, all CSS files will be c oncatenate d into a s ingle mini fied `.css ` file in the build output. | |
512 | ||
513 | If you are concerned about usi ng Webpack -specific semantics, you can p ut all you r CSS righ t into `sr c/index.cs s`. It wou ld still b e imported from `src /index.js` , but you could alwa ys remove that impor t if you l ater migra te to a di fferent bu ild tool. | |
514 | ||
515 | ## Post-Pr ocessing C SS | |
516 | ||
517 | This proje ct setup m inifies yo ur CSS and adds vend or prefixe s to it au tomaticall y through [Autoprefi xer](https ://github. com/postcs s/autopref ixer) so y ou don’t need to w orry about it. | |
518 | ||
519 | For exampl e, this: | |
520 | ||
521 | ```css | |
522 | .App { | |
523 | display: flex; | |
524 | flex-dir ection: ro w; | |
525 | align-it ems: cente r; | |
526 | } | |
527 | ``` | |
528 | ||
529 | becomes th is: | |
530 | ||
531 | ```css | |
532 | .App { | |
533 | display: -webkit-b ox; | |
534 | display: -ms-flexb ox; | |
535 | display: flex; | |
536 | -webkit- box-orient : horizont al; | |
537 | -webkit- box-direct ion: norma l; | |
538 | -ms- flex-direc tion: row; | |
539 | flex-direc tion: row; | |
540 | -webkit- box-align: center; | |
541 | -ms- flex-align : center; | |
542 | align-item s: center; | |
543 | } | |
544 | ``` | |
545 | ||
546 | If you nee d to disab le autopre fixing for some reas on, [follo w this sec tion](http s://github .com/postc ss/autopre fixer#disa bling). | |
547 | ||
548 | ## Adding a CSS Prep rocessor ( Sass, Less etc.) | |
549 | ||
550 | Generally, we recomm end that y ou don’t reuse the same CSS classes ac ross diffe rent compo nents. For example, instead of using a ` .Button` C SS class i n `<Accept Button>` a nd `<Rejec tButton>` components , we recom mend creat ing a `<Bu tton>` com ponent wit h its own `.Button` styles, th at both `< AcceptButt on>` and ` <RejectBut ton>` can render (bu t [not inh erit](http s://facebo ok.github. io/react/d ocs/compos ition-vs-i nheritance .html)). | |
551 | ||
552 | Following this rule often make s CSS prep rocessors less usefu l, as feat ures like mixins and nesting a re replace d by compo nent compo sition. Yo u can, how ever, inte grate a CS S preproce ssor if yo u find it valuable. In this wa lkthrough, we will b e using Sa ss, but yo u can also use Less, or anothe r alternat ive. | |
553 | ||
554 | First, let ’s insta ll the com mand-line interface for Sass: | |
555 | ||
556 | ```sh | |
557 | npm instal l --save n ode-sass-c hokidar | |
558 | ``` | |
559 | ||
560 | Alternativ ely you ma y use `yar n`: | |
561 | ||
562 | ```sh | |
563 | yarn add n ode-sass-c hokidar | |
564 | ``` | |
565 | ||
566 | Then in `p ackage.jso n`, add th e followin g lines to `scripts` : | |
567 | ||
568 | ```diff | |
569 | "script s": { | |
570 | + "buil d-css": "n ode-sass-c hokidar sr c/ -o src/ ", | |
571 | + "watc h-css": "n pm run bui ld-css && node-sass- chokidar s rc/ -o src / --watch --recursiv e", | |
572 | "star t": "react -scripts s tart", | |
573 | "buil d": "react -scripts b uild", | |
574 | "test ": "react- scripts te st --env=j sdom", | |
575 | ``` | |
576 | ||
577 | >Note: To use a diff erent prep rocessor, replace `b uild-css` and `watch -css` comm ands accor ding to yo ur preproc essor’s documentat ion. | |
578 | ||
579 | Now you ca n rename ` src/App.cs s` to `src /App.scss` and run ` npm run wa tch-css`. The watche r will fin d every Sa ss file in `src` sub directorie s, and cre ate a corr esponding CSS file n ext to it, in our ca se overwri ting `src/ App.css`. Since `src /App.js` s till impor ts `src/Ap p.css`, th e styles b ecome a pa rt of your applicati on. You ca n now edit `src/App. scss`, and `src/App. css` will be regener ated. | |
580 | ||
581 | To share v ariables b etween Sas s files, y ou can use Sass impo rts. For e xample, `s rc/App.scs s` and oth er compone nt style f iles could include ` @import ". /shared.sc ss";` with variable definition s. | |
582 | ||
583 | To enable importing files with out using relative p aths, you can add th e `--incl ude-path` option to the comman d in `pack age.json`. | |
584 | ||
585 | ``` | |
586 | "build-css ": "node-s ass-chokid ar --inclu de-path ./ src --incl ude-path . /node_modu les src/ - o src/", | |
587 | "watch-css ": "npm ru n build-cs s && node- sass-choki dar --incl ude-path . /src --inc lude-path ./node_mod ules src/ -o src/ -- watch --re cursive", | |
588 | ``` | |
589 | ||
590 | This will allow you to do impo rts like | |
591 | ||
592 | ```scss | |
593 | @import 's tyles/_col ors.scss'; // assumi ng a style s director y under sr c/ | |
594 | @import 'n progress/n progress'; // import ing a css file from the nprogr ess node m odule | |
595 | ``` | |
596 | ||
597 | At this po int you mi ght want t o remove a ll CSS fil es from th e source c ontrol, an d add `src /**/*.css` to your ` .gitignore ` file. It is genera lly a good practice to keep th e build pr oducts out side of th e source c ontrol. | |
598 | ||
599 | As a final step, you may find it conveni ent to run `watch-cs s` automat ically wit h `npm sta rt`, and r un `build- css` as a part of `n pm run bui ld`. You c an use the `&&` oper ator to ex ecute two scripts se quentially . However, there is no cross-p latform wa y to run t wo scripts in parall el, so we will insta ll a packa ge for thi s: | |
600 | ||
601 | ```sh | |
602 | npm instal l --save n pm-run-all | |
603 | ``` | |
604 | ||
605 | Alternativ ely you ma y use `yar n`: | |
606 | ||
607 | ```sh | |
608 | yarn add n pm-run-all | |
609 | ``` | |
610 | ||
611 | Then we ca n change ` start` and `build` s cripts to include th e CSS prep rocessor c ommands: | |
612 | ||
613 | ```diff | |
614 | "script s": { | |
615 | "buil d-css": "n ode-sass-c hokidar sr c/ -o src/ ", | |
616 | "watc h-css": "n pm run bui ld-css && node-sass- chokidar s rc/ -o src / --watch --recursiv e", | |
617 | - "star t": "react -scripts s tart", | |
618 | - "buil d": "react -scripts b uild", | |
619 | + "star t-js": "re act-script s start", | |
620 | + "star t": "npm-r un-all -p watch-css start-js", | |
621 | + "buil d-js": "re act-script s build", | |
622 | + "buil d": "npm-r un-all bui ld-css bui ld-js", | |
623 | "test ": "react- scripts te st --env=j sdom", | |
624 | "ejec t": "react -scripts e ject" | |
625 | } | |
626 | ``` | |
627 | ||
628 | Now runnin g `npm sta rt` and `n pm run bui ld` also b uilds Sass files. | |
629 | ||
630 | **Why `nod e-sass-cho kidar`?** | |
631 | ||
632 | `node-sass ` has been reported as having the follow ing issues : | |
633 | ||
634 | - `node-sa ss --watch ` has been reported to have *p erformance issues* i n certain conditions when used in a virt ual machin e or with docker. | |
635 | ||
636 | - Infinite styles co mpiling [# 1939](http s://github .com/faceb ookincubat or/create- react-app/ issues/193 9) | |
637 | ||
638 | - `node-sa ss` has be en reporte d as havin g issues w ith detect ing new fi les in a d irectory [ #1891](htt ps://githu b.com/sass /node-sass /issues/18 91) | |
639 | ||
640 | `node-sas s-chokidar ` is used here as it addresses these iss ues. | |
641 | ||
642 | ## Adding Images, Fo nts, and F iles | |
643 | ||
644 | With Webpa ck, using static ass ets like i mages and fonts work s similarl y to CSS. | |
645 | ||
646 | You can ** `import` a file righ t in a Jav aScript mo dule**. Th is tells W ebpack to include th at file in the bundl e. Unlike CSS import s, importi ng a file gives you a string v alue. This value is the final path you c an referen ce in your code, e.g . as the ` src` attri bute of an image or the `href` of a link to a PDF. | |
647 | ||
648 | To reduce the number of reques ts to the server, im porting im ages that are less t han 10,000 bytes ret urns a [da ta URI](ht tps://deve loper.mozi lla.org/en -US/docs/W eb/HTTP/Ba sics_of_HT TP/Data_UR Is) instea d of a pat h. This ap plies to t he followi ng file ex tensions: bmp, gif, jpg, jpeg, and png. SVG files are exclud ed due to [#1153](ht tps://gith ub.com/fac ebookincub ator/creat e-react-ap p/issues/1 153). | |
649 | ||
650 | Here is an example: | |
651 | ||
652 | ```js | |
653 | import Rea ct from 'r eact'; | |
654 | import log o from './ logo.png'; // Tell W ebpack thi s JS file uses this image | |
655 | ||
656 | console.lo g(logo); / / /logo.84 287d09.png | |
657 | ||
658 | function H eader() { | |
659 | // Impor t result i s the URL of your im age | |
660 | return < img src={l ogo} alt=" Logo" />; | |
661 | } | |
662 | ||
663 | export def ault Heade r; | |
664 | ``` | |
665 | ||
666 | This ensur es that wh en the pro ject is bu ilt, Webpa ck will co rrectly mo ve the ima ges into t he build f older, and provide u s with cor rect paths . | |
667 | ||
668 | This works in CSS to o: | |
669 | ||
670 | ```css | |
671 | .Logo { | |
672 | backgrou nd-image: url(./logo .png); | |
673 | } | |
674 | ``` | |
675 | ||
676 | Webpack fi nds all re lative mod ule refere nces in CS S (they st art with ` ./`) and r eplaces th em with th e final pa ths from t he compile d bundle. If you mak e a typo o r accident ally delet e an impor tant file, you will see a comp ilation er ror, just like when you import a non-exi stent Java Script mod ule. The f inal filen ames in th e compiled bundle ar e generate d by Webpa ck from co ntent hash es. If the file cont ent change s in the f uture, Web pack will give it a different name in pr oduction s o you donâ €™t need t o worry ab out long-t erm cachin g of asset s. | |
677 | ||
678 | Please be advised th at this is also a cu stom featu re of Webp ack. | |
679 | ||
680 | **It is no t required for React ** but man y people e njoy it (a nd React N ative uses a similar mechanism for image s).<br> | |
681 | An alterna tive way o f handling static as sets is de scribed in the next section. | |
682 | ||
683 | ## Using t he `public ` Folder | |
684 | ||
685 | >Note: thi s feature is availab le with `r eact-scrip ts@0.5.0` and higher . | |
686 | ||
687 | ### Changi ng the HTM L | |
688 | ||
689 | The `publi c` folder contains t he HTML fi le so you can tweak it, for ex ample, to [set the p age title] (#changing -the-page- title). | |
690 | The `<scri pt>` tag w ith the co mpiled cod e will be added to i t automati cally duri ng the bui ld process . | |
691 | ||
692 | ### Adding Assets Ou tside of t he Module System | |
693 | ||
694 | You can al so add oth er assets to the `pu blic` fold er. | |
695 | ||
696 | Note that we normall y encourag e you to ` import` as sets in Ja vaScript f iles inste ad. | |
697 | For exampl e, see the sections on [adding a stylesh eet](#addi ng-a-style sheet) and [adding i mages and fonts](#ad ding-image s-fonts-an d-files). | |
698 | This mecha nism provi des a numb er of bene fits: | |
699 | ||
700 | * Scripts and styles heets get minified a nd bundled together to avoid e xtra netwo rk request s. | |
701 | * Missing files caus e compilat ion errors instead o f 404 erro rs for you r users. | |
702 | * Result f ilenames i nclude con tent hashe s so you d on’t nee d to worry about bro wsers cach ing their old versio ns. | |
703 | ||
704 | However th ere is an **escape h atch** tha t you can use to add an asset outside of the modul e system. | |
705 | ||
706 | If you put a file in to the `pu blic` fold er, it wil l **not** be process ed by Webp ack. Inste ad it will be copied into the build fold er untouch ed. To r eference a ssets in t he `public ` folder, you need t o use a sp ecial vari able calle d `PUBLIC_ URL`. | |
707 | ||
708 | Inside `in dex.html`, you can u se it like this: | |
709 | ||
710 | ```html | |
711 | <link rel= "shortcut icon" href ="%PUBLIC_ URL%/favic on.ico"> | |
712 | ``` | |
713 | ||
714 | Only files inside th e `public` folder wi ll be acce ssible by `%PUBLIC_U RL%` prefi x. If you need to us e a file f rom `src` or `node_m odules`, y ou’ll ha ve to copy it there to explici tly specif y your int ention to make this file a par t of the b uild. | |
715 | ||
716 | When you r un `npm ru n build`, Create Rea ct App wil l substitu te `%PUBLI C_URL%` wi th a corre ct absolut e path so your proje ct works e ven if you use clien t-side rou ting or ho st it at a non-root URL. | |
717 | ||
718 | In JavaScr ipt code, you can us e `process .env.PUBLI C_URL` for similar p urposes: | |
719 | ||
720 | ```js | |
721 | render() { | |
722 | // Note: this is a n escape h atch and s hould be u sed sparin gly! | |
723 | // Norma lly we rec ommend usi ng `import ` for gett ing asset URLs | |
724 | // as de scribed in “Adding Images an d Fonts†above thi s section. | |
725 | return < img src={p rocess.env .PUBLIC_UR L + '/img/ logo.png'} />; | |
726 | } | |
727 | ``` | |
728 | ||
729 | Keep in mi nd the dow nsides of this appro ach: | |
730 | ||
731 | * None of the files in `public ` folder g et post-pr ocessed or minified. | |
732 | * Missing files will not be ca lled at co mpilation time, and will cause 404 error s for your users. | |
733 | * Result f ilenames w on’t inc lude conte nt hashes so you’l l need to add query arguments or rename them every time they change. | |
734 | ||
735 | ### When t o Use the `public` F older | |
736 | ||
737 | Normally w e recommen d importin g [stylesh eets](#add ing-a-styl esheet), [ images, an d fonts](# adding-ima ges-fonts- and-files) from Java Script. | |
738 | The `publi c` folder is useful as a worka round for a number o f less com mon cases: | |
739 | ||
740 | * You need a file wi th a speci fic name i n the buil d output, such as [` manifest.w ebmanifest `](https:/ /developer .mozilla.o rg/en-US/d ocs/Web/Ma nifest). | |
741 | * You have thousands of images and need to dynamic ally refer ence their paths. | |
742 | * You want to includ e a small script lik e [`pace.j s`](http:/ /github.hu bspot.com/ pace/docs/ welcome/) outside of the bundl ed code. | |
743 | * Some lib rary may b e incompat ible with Webpack an d you have no other option but to includ e it as a `<script>` tag. | |
744 | ||
745 | Note that if you add a `<scrip t>` that d eclares gl obal varia bles, you also need to read th e next sec tion on us ing them. | |
746 | ||
747 | ## Using G lobal Vari ables | |
748 | ||
749 | When you i nclude a s cript in t he HTML fi le that de fines glob al variabl es and try to use on e of these variables in the co de, the li nter will complain b ecause it cannot see the defin ition of t he variabl e. | |
750 | ||
751 | You can av oid this b y reading the global variable explicitly from the `window` o bject, for example: | |
752 | ||
753 | ```js | |
754 | const $ = window.$; | |
755 | ``` | |
756 | ||
757 | This makes it obviou s you are using a gl obal varia ble intent ionally ra ther than because of a typo. | |
758 | ||
759 | Alternativ ely, you c an force t he linter to ignore any line b y adding ` // eslint- disable-li ne` after it. | |
760 | ||
761 | ## Adding Bootstrap | |
762 | ||
763 | You don’ t have to use [React Bootstrap ](https:// react-boot strap.gith ub.io) tog ether with React but it is a p opular lib rary for i ntegrating Bootstrap with Reac t apps. If you need it, you ca n integrat e it with Create Rea ct App by following these step s: | |
764 | ||
765 | Install Re act Bootst rap and Bo otstrap fr om npm. Re act Bootst rap does n ot include Bootstrap CSS so th is needs t o be insta lled as we ll: | |
766 | ||
767 | ```sh | |
768 | npm instal l --save r eact-boots trap boots trap@3 | |
769 | ``` | |
770 | ||
771 | Alternativ ely you ma y use `yar n`: | |
772 | ||
773 | ```sh | |
774 | yarn add r eact-boots trap boots trap@3 | |
775 | ``` | |
776 | ||
777 | Import Boo tstrap CSS and optio nally Boot strap them e CSS in t he beginni ng of your ```src/in dex.js``` file: | |
778 | ||
779 | ```js | |
780 | import 'bo otstrap/di st/css/boo tstrap.css '; | |
781 | import 'bo otstrap/di st/css/boo tstrap-the me.css'; | |
782 | // Put any other imp orts below so that C SS from yo ur | |
783 | // compone nts takes precedence over defa ult styles . | |
784 | ``` | |
785 | ||
786 | Import req uired Reac t Bootstra p componen ts within ```src/App .js``` fil e or your custom com ponent fil es: | |
787 | ||
788 | ```js | |
789 | import { N avbar, Jum botron, Bu tton } fro m 'react-b ootstrap'; | |
790 | ``` | |
791 | ||
792 | Now you ar e ready to use the i mported Re act Bootst rap compon ents withi n your com ponent hie rarchy def ined in th e render m ethod. Her e is an ex ample [`Ap p.js`](htt ps://gist. githubuser content.co m/gaearon/ 85d8c067f6 af1e56277c 82d19fd4da 7b/raw/615 8dd991b672 84e9fc8d70 b9d973efe8 7659d72/Ap p.js) redo ne using R eact Boots trap. | |
793 | ||
794 | ### Using a Custom T heme | |
795 | ||
796 | Sometimes you might need to tw eak the vi sual style s of Boots trap (or e quivalent package).< br> | |
797 | We suggest the follo wing appro ach: | |
798 | ||
799 | * Create a new packa ge that de pends on t he package you wish to customi ze, e.g. B ootstrap. | |
800 | * Add the necessary build step s to tweak the theme , and publ ish your p ackage on npm. | |
801 | * Install your own t heme npm p ackage as a dependen cy of your app. | |
802 | ||
803 | Here is an example o f adding a [customiz ed Bootstr ap](https: //medium.c om/@tacoma nator/cust omizing-cr eate-react -app-aa9ff b88165) th at follows these ste ps. | |
804 | ||
805 | ## Adding Flow | |
806 | ||
807 | Flow is a static typ e checker that helps you write code with fewer bug s. Check o ut this [i ntroductio n to using static ty pes in Jav aScript](h ttps://med ium.com/@p reethikasi reddy/why- use-static -types-in- javascript -part-1-83 82da1e0adb ) if you a re new to this conce pt. | |
808 | ||
809 | Recent ver sions of [ Flow](http ://flowtyp e.org/) wo rk with Cr eate React App proje cts out of the box. | |
810 | ||
811 | To add Flo w to a Cre ate React App projec t, follow these step s: | |
812 | ||
813 | 1. Run `np m install --save flo w-bin` (or `yarn add flow-bin` ). | |
814 | 2. Add `"f low": "flo w"` to the `scripts` section o f your `pa ckage.json `. | |
815 | 3. Run `np m run flow init` (or `yarn flo w init`) t o create a [`.flowco nfig` file ](https:// flowtype.o rg/docs/ad vanced-con figuration .html) in the root d irectory. | |
816 | 4. Add `// @flow` to any files you want to type ch eck (for e xample, to `src/App. js`). | |
817 | ||
818 | Now you ca n run `npm run flow` (or `yarn flow`) to check the files for type erro rs. | |
819 | You can op tionally u se an IDE like [Nucl ide](https ://nuclide .io/docs/l anguages/f low/) for a better i ntegrated experience . | |
820 | In the fut ure we pla n to integ rate it in to Create React App even more closely. | |
821 | ||
822 | To learn m ore about Flow, chec k out [its documenta tion](http s://flowty pe.org/). | |
823 | ||
824 | ## Adding a Router | |
825 | ||
826 | Create Rea ct App doe sn't presc ribe a spe cific rout ing soluti on, but [R eact Route r](https:/ /reacttrai ning.com/r eact-route r/) is the most popu lar one. | |
827 | ||
828 | To add it, run: | |
829 | ||
830 | ```sh | |
831 | npm instal l --save r eact-route r-dom | |
832 | ``` | |
833 | ||
834 | Alternativ ely you ma y use `yar n`: | |
835 | ||
836 | ```sh | |
837 | yarn add r eact-route r-dom | |
838 | ``` | |
839 | ||
840 | To try it, delete al l the code in `src/A pp.js` and replace i t with any of the ex amples on its websit e. The [Ba sic Exampl e](https:/ /reacttrai ning.com/r eact-route r/web/exam ple/basic) is a good place to get starte d. | |
841 | ||
842 | Note that [you may n eed to con figure you r producti on server to support client-si de routing ](#serving -apps-with -client-si de-routing ) before d eploying y our app. | |
843 | ||
844 | ## Adding Custom Env ironment V ariables | |
845 | ||
846 | >Note: thi s feature is availab le with `r eact-scrip ts@0.2.3` and higher . | |
847 | ||
848 | Your proje ct can con sume varia bles decla red in you r environm ent as if they were declared l ocally in your JS fi les. By | |
849 | default yo u will hav e `NODE_EN V` defined for you, and any ot her enviro nment vari ables star ting with | |
850 | `REACT_APP _`. | |
851 | ||
852 | **The envi ronment va riables ar e embedded during th e build ti me**. Sinc e Create R eact App p roduces a static HTM L/CSS/JS b undle, it can’t po ssibly rea d them at runtime. T o read the m at runti me, you wo uld need t o load HTM L into mem ory on the server an d replace placeholde rs in runt ime, just like [desc ribed here ](#injecti ng-data-fr om-the-ser ver-into-t he-page). Alternativ ely you ca n rebuild the app on the serve r anytime you change them. | |
853 | ||
854 | >Note: You must crea te custom environmen t variable s beginnin g with `RE ACT_APP_`. Any other variables except `N ODE_ENV` w ill be ign ored to av oid accide ntally [ex posing a p rivate key on the ma chine that could hav e the same name](htt ps://githu b.com/face bookincuba tor/create -react-app /issues/86 5#issuecom ment-25219 9527). Cha nging any environmen t variable s will req uire you t o restart the develo pment serv er if it i s running. | |
855 | ||
856 | These envi ronment va riables wi ll be defi ned for yo u on `proc ess.env`. For exampl e, having an environ ment | |
857 | variable n amed `REAC T_APP_SECR ET_CODE` w ill be exp osed in yo ur JS as ` process.en v.REACT_AP P_SECRET_C ODE`. | |
858 | ||
859 | There is a lso a spec ial built- in environ ment varia ble called `NODE_ENV `. You can read it f rom `proce ss.env.NOD E_ENV`. Wh en you run `npm star t`, it is always equ al to `'de velopment' `, when yo u run `npm test` it is always equal to ` 'test'`, a nd when yo u run `npm run build ` to make a producti on bundle, it is alw ays equal to `'produ ction'`. * *You canno t override `NODE_ENV ` manually .** This p revents de velopers f rom accide ntally dep loying a s low develo pment buil d to produ ction. | |
860 | ||
861 | These envi ronment va riables ca n be usefu l for disp laying inf ormation c onditional ly based o n where th e project is | |
862 | deployed o r consumin g sensitiv e data tha t lives ou tside of v ersion con trol. | |
863 | ||
864 | First, you need to h ave enviro nment vari ables defi ned. For e xample, le t’s say you wanted to consum e a PW defined | |
865 | in the env ironment i nside a `< form>`: | |
866 | ||
867 | ```jsx | |
868 | render() { | |
869 | return ( | |
870 | <div> | |
871 | <sma ll>You are running t his applic ation in < b>{process .env.NODE_ ENV}</b> m ode.</smal l> | |
872 | <for m> | |
873 | <i nput type= "hidden" d efaultValu e={process .env.REACT _APP_SECRE T_CODE} /> | |
874 | </fo rm> | |
875 | </div> | |
876 | ); | |
877 | } | |
878 | ``` | |
879 | ||
880 | During the build, `p rocess.env .REACT_APP _SECRET_CO DE` will b e replaced with the current va lue of the `REACT_AP P_SECRET_C ODE` envir onment var iable. Rem ember that the `NODE _ENV` vari able will be set for you autom atically. | |
881 | ||
882 | When you l oad the ap p in the b rowser and inspect t he `<input >`, you wi ll see its value set to `abcde f`, and th e bold tex t will sho w the envi ronment pr ovided whe n using `n pm start`: | |
883 | ||
884 | ```html | |
885 | <div> | |
886 | <small>Y ou are run ning this applicatio n in <b>de velopment< /b> mode.< /small> | |
887 | <form> | |
888 | <input type="hid den" value ="abcdef" /> | |
889 | </form> | |
890 | </div> | |
891 | ``` | |
892 | ||
893 | The above form is lo oking for a variable called `R EACT_APP_S ECRET_CODE ` from the environme nt. In ord er to cons ume this | |
894 | value, we need to ha ve it defi ned in the environme nt. This c an be done using two ways: eit her in you r shell or in | |
895 | a `.env` f ile. Both of these w ays are de scribed in the next few sectio ns. | |
896 | ||
897 | Having acc ess to the `NODE_ENV ` is also useful for performin g actions conditiona lly: | |
898 | ||
899 | ```js | |
900 | if (proces s.env.NODE _ENV !== ' production ') { | |
901 | analytic s.disable( ); | |
902 | } | |
903 | ``` | |
904 | ||
905 | When you c ompile the app with `npm run b uild`, the minificat ion step w ill strip out this c ondition, and the re sulting bu ndle will be smaller . | |
906 | ||
907 | ### Refere ncing Envi ronment Va riables in the HTML | |
908 | ||
909 | >Note: thi s feature is availab le with `r eact-scrip ts@0.9.0` and higher . | |
910 | ||
911 | You can al so access the enviro nment vari ables star ting with `REACT_APP _` in the `public/in dex.html`. For examp le: | |
912 | ||
913 | ```html | |
914 | <title>%RE ACT_APP_WE BSITE_NAME %</title> | |
915 | ``` | |
916 | ||
917 | Note that the caveat s from the above sec tion apply : | |
918 | ||
919 | * Apart fr om a few b uilt-in va riables (` NODE_ENV` and `PUBLI C_URL`), v ariable na mes must s tart with `REACT_APP _` to work . | |
920 | * The envi ronment va riables ar e injected at build time. If y ou need to inject th em at runt ime, [foll ow this ap proach ins tead](#gen erating-dy namic-meta -tags-on-t he-server) . | |
921 | ||
922 | ### Adding Temporary Environme nt Variabl es In Your Shell | |
923 | ||
924 | Defining e nvironment variables can vary between OS es. It’s also impo rtant to k now that t his manner is tempor ary for th e | |
925 | life of th e shell se ssion. | |
926 | ||
927 | #### Windo ws (cmd.ex e) | |
928 | ||
929 | ```cmd | |
930 | set "REACT _APP_SECRE T_CODE=abc def" && np m start | |
931 | ``` | |
932 | ||
933 | (Note: Quo tes around the varia ble assign ment are r equired to avoid a t railing wh itespace.) | |
934 | ||
935 | #### Windo ws (Powers hell) | |
936 | ||
937 | ```Powersh ell | |
938 | ($env:REAC T_APP_SECR ET_CODE = "abcdef") -and (npm start) | |
939 | ``` | |
940 | ||
941 | #### Linux , macOS (B ash) | |
942 | ||
943 | ```bash | |
944 | REACT_APP_ SECRET_COD E=abcdef n pm start | |
945 | ``` | |
946 | ||
947 | ### Adding Developme nt Environ ment Varia bles In `. env` | |
948 | ||
949 | >Note: thi s feature is availab le with `r eact-scrip ts@0.5.0` and higher . | |
950 | ||
951 | To define permanent environmen t variable s, create a file cal led `.env` in the ro ot of your project: | |
952 | ||
953 | ``` | |
954 | REACT_APP_ SECRET_COD E=abcdef | |
955 | ``` | |
956 | >Note: You must crea te custom environmen t variable s beginnin g with `RE ACT_APP_`. Any other variables except `N ODE_ENV` w ill be ign ored to av oid [accid entally ex posing a p rivate key on the ma chine that could hav e the same name](htt ps://githu b.com/face bookincuba tor/create -react-app /issues/86 5#issuecom ment-25219 9527). Cha nging any environmen t variable s will req uire you t o restart the develo pment serv er if it i s running. | |
957 | ||
958 | `.env` fil es **shoul d be** che cked into source con trol (with the exclu sion of `. env*.local `). | |
959 | ||
960 | #### What other `.en v` files c an be used ? | |
961 | ||
962 | >Note: thi s feature is **avail able with `react-scr ipts@1.0.0 ` and high er**. | |
963 | ||
964 | * `.env`: Default. | |
965 | * `.env.lo cal`: Loca l override s. **This file is lo aded for a ll environ ments exce pt test.** | |
966 | * `.env.de velopment` , `.env.te st`, `.env .productio n`: Enviro nment-spec ific setti ngs. | |
967 | * `.env.de velopment. local`, `. env.test.l ocal`, `.e nv.product ion.local` : Local ov errides of environme nt-specifi c settings . | |
968 | ||
969 | Files on t he left ha ve more pr iority tha n files on the right : | |
970 | ||
971 | * `npm sta rt`: `.env .developme nt.local`, `.env.dev elopment`, `.env.loc al`, `.env ` | |
972 | * `npm run build`: ` .env.produ ction.loca l`, `.env. production `, `.env.l ocal`, `.e nv` | |
973 | * `npm tes t`: `.env. test.local `, `.env.t est`, `.en v` (note ` .env.local ` is missi ng) | |
974 | ||
975 | These vari ables will act as th e defaults if the ma chine does not expli citly set them.<br> | |
976 | Please ref er to the [dotenv do cumentatio n](https:/ /github.co m/motdotla /dotenv) f or more de tails. | |
977 | ||
978 | >Note: If you are de fining env ironment v ariables f or develop ment, your CI and/or hosting p latform wi ll most li kely need | |
979 | these defi ned as wel l. Consult their doc umentation how to do this. For example, see the do cumentatio n for [Tra vis CI](ht tps://docs .travis-ci .com/user/ environmen t-variable s/) or [He roku](http s://devcen ter.heroku .com/artic les/config -vars). | |
980 | ||
981 | #### Expan ding Envir onment Var iables In `.env` | |
982 | ||
983 | >Note: thi s feature is availab le with `r eact-scrip ts@1.1.0` and higher . | |
984 | ||
985 | Expand var iables alr eady on yo ur machine for use i n your `.e nv` file ( using [dot env-expand ](https:// github.com /motdotla/ dotenv-exp and)). | |
986 | ||
987 | For exampl e, to get the enviro nment vari able `npm_ package_ve rsion`: | |
988 | ||
989 | ``` | |
990 | REACT_APP_ VERSION=$n pm_package _version | |
991 | # also wor ks: | |
992 | # REACT_AP P_VERSION= ${npm_pack age_versio n} | |
993 | ``` | |
994 | ||
995 | Or expand variables local to t he current `.env` fi le: | |
996 | ||
997 | ``` | |
998 | DOMAIN=www .example.c om | |
999 | REACT_APP_ FOO=$DOMAI N/foo | |
1000 | REACT_APP_ BAR=$DOMAI N/bar | |
1001 | ``` | |
1002 | ||
1003 | ## Can I U se Decorat ors? | |
1004 | ||
1005 | Many popul ar librari es use [de corators]( https://me dium.com/g oogle-deve lopers/exp loring-es7 -decorator s-76ecb65f b841) in t heir docum entation.< br> | |
1006 | Create Rea ct App doe sn’t sup port decor ator synta x at the m oment beca use: | |
1007 | ||
1008 | * It is an experimen tal propos al and is subject to change. | |
1009 | * The curr ent specif ication ve rsion is n ot officia lly suppor ted by Bab el. | |
1010 | * If the s pecificati on changes , we won†™t be able to write a codemod because we don’t u se them in ternally a t Facebook . | |
1011 | ||
1012 | However in many case s you can rewrite de corator-ba sed code w ithout dec orators ju st as fine .<br> | |
1013 | Please ref er to thes e two thre ads for re ference: | |
1014 | ||
1015 | * [#214](h ttps://git hub.com/fa cebookincu bator/crea te-react-a pp/issues/ 214) | |
1016 | * [#411](h ttps://git hub.com/fa cebookincu bator/crea te-react-a pp/issues/ 411) | |
1017 | ||
1018 | Create Rea ct App wil l add deco rator supp ort when t he specifi cation adv ances to a stable st age. | |
1019 | ||
1020 | ## Fetchin g Data wit h AJAX Req uests | |
1021 | ||
1022 | React does n't prescr ibe a spec ific appro ach to dat a fetching , but peop le commonl y use eith er a libra ry like [a xios](http s://github .com/axios /axios) or the [`fet ch()` API] (https://d eveloper.m ozilla.org /en-US/doc s/Web/API/ Fetch_API) provided by the bro wser. Conv eniently, Create Rea ct App inc ludes a po lyfill for `fetch()` so you ca n use it w ithout wor rying abou t the brow ser suppor t. | |
1023 | ||
1024 | The global `fetch` f unction al lows to ea sily makes AJAX requ ests. It t akes in a URL as an input and returns a `Promise` that resol ves to a ` Response` object. Yo u can find more info rmation ab out `fetch ` [here](h ttps://dev eloper.moz illa.org/e n-US/docs/ Web/API/Fe tch_API/Us ing_Fetch) . | |
1025 | ||
1026 | This proje ct also in cludes a [ Promise po lyfill](ht tps://gith ub.com/the n/promise) which pro vides a fu ll impleme ntation of Promises/ A+. A Prom ise repres ents the e ventual re sult of an asynchron ous operat ion, you c an find mo re informa tion about Promises [here](htt ps://www.p romisejs.o rg/) and [ here](http s://develo per.mozill a.org/en-U S/docs/Web /JavaScrip t/Referenc e/Global_O bjects/Pro mise). Bot h axios an d `fetch() ` use Prom ises under the hood. You can a lso use th e [`async / await`]( https://da vidwalsh.n ame/async- await) syn tax to red uce the ca llback nes ting. | |
1027 | ||
1028 | You can le arn more a bout makin g AJAX req uests from React com ponents in [the FAQ entry on t he React w ebsite](ht tps://reac tjs.org/do cs/faq-aja x.html). | |
1029 | ||
1030 | ## Integra ting with an API Bac kend | |
1031 | ||
1032 | These tuto rials will help you to integra te your ap p with an API backen d running on another port, | |
1033 | using `fet ch()` to a ccess it. | |
1034 | ||
1035 | ### Node | |
1036 | Check out [this tuto rial](http s://www.fu llstackrea ct.com/art icles/usin g-create-r eact-app-w ith-a-serv er/). | |
1037 | You can fi nd the com panion Git Hub reposi tory [here ](https:// github.com /fullstack react/food -lookup-de mo). | |
1038 | ||
1039 | ### Ruby o n Rails | |
1040 | ||
1041 | Check out [this tuto rial](http s://www.fu llstackrea ct.com/art icles/how- to-get-cre ate-react- app-to-wor k-with-you r-rails-ap i/). | |
1042 | You can fi nd the com panion Git Hub reposi tory [here ](https:// github.com /fullstack react/food -lookup-de mo-rails). | |
1043 | ||
1044 | ## Proxyin g API Requ ests in De velopment | |
1045 | ||
1046 | >Note: thi s feature is availab le with `r eact-scrip ts@0.2.3` and higher . | |
1047 | ||
1048 | People oft en serve t he front-e nd React a pp from th e same hos t and port as their backend im plementati on.<br> | |
1049 | For exampl e, a produ ction setu p might lo ok like th is after t he app is deployed: | |
1050 | ||
1051 | ``` | |
1052 | / - stat ic server returns in dex.html w ith React app | |
1053 | /todos - stat ic server returns in dex.html w ith React app | |
1054 | /api/todos - serv er handles any /api/ * requests using the backend i mplementat ion | |
1055 | ``` | |
1056 | ||
1057 | Such setup is **not* * required . However, if you ** do** have a setup li ke this, i t is conve nient to w rite reque sts like ` fetch('/ap i/todos')` without w orrying ab out redire cting them to anothe r host or port durin g developm ent. | |
1058 | ||
1059 | To tell th e developm ent server to proxy any unknow n requests to your A PI server in develop ment, add a `proxy` field to y our `packa ge.json`, for exampl e: | |
1060 | ||
1061 | ```js | |
1062 | "proxy": "http://l ocalhost:4 000", | |
1063 | ``` | |
1064 | ||
1065 | This way, when you ` fetch('/ap i/todos')` in develo pment, the developme nt server will recog nize that it’s not a static asset, and will prox y your req uest to `h ttp://loca lhost:4000 /api/todos ` as a fal lback. The developme nt server will **onl y** attemp t to send requests w ithout `te xt/html` i n its `Acc ept` heade r to the p roxy. | |
1066 | ||
1067 | Convenient ly, this a voids [COR S issues]( http://sta ckoverflow .com/quest ions/21854 516/unders tanding-aj ax-cors-an d-security -considera tions) and error mes sages like this in d evelopment : | |
1068 | ||
1069 | ``` | |
1070 | Fetch API cannot loa d http://l ocalhost:4 000/api/to dos. No 'A ccess-Cont rol-Allow- Origin' he ader is pr esent on t he request ed resourc e. Origin 'http://lo calhost:30 00' is the refore not allowed a ccess. If an opaque response s erves your needs, se t the requ est's mode to 'no-co rs' to fet ch the res ource with CORS disa bled. | |
1071 | ``` | |
1072 | ||
1073 | Keep in mi nd that `p roxy` only has effec t in devel opment (wi th `npm st art`), and it is up to you to ensure tha t URLs lik e `/api/to dos` point to the ri ght thing in product ion. You d on’t hav e to use t he `/api` prefix. An y unrecogn ized reque st without a `text/h tml` accep t header w ill be red irected to the speci fied `prox y`. | |
1074 | ||
1075 | The `proxy ` option s upports HT TP, HTTPS and WebSoc ket connec tions.<br> | |
1076 | If the `pr oxy` optio n is **not ** flexibl e enough f or you, al ternativel y you can: | |
1077 | ||
1078 | * [Configu re the pro xy yoursel f](#config uring-the- proxy-manu ally) | |
1079 | * Enable C ORS on you r server ( [here’s how to do it for Exp ress](http ://enable- cors.org/s erver_expr essjs.html )). | |
1080 | * Use [env ironment v ariables]( #adding-cu stom-envir onment-var iables) to inject th e right se rver host and port i nto your a pp. | |
1081 | ||
1082 | ### "Inval id Host He ader" Erro rs After C onfiguring Proxy | |
1083 | ||
1084 | When you e nable the `proxy` op tion, you opt into a more stri ct set of host check s. This is necessary because l eaving the backend o pen to rem ote hosts makes your computer vulnerable to DNS re binding at tacks. The issue is explained in [this a rticle](ht tps://medi um.com/web pack/webpa ck-dev-ser ver-middle ware-secur ity-issues -1489d9508 74a) and [ this issue ](https:// github.com /webpack/w ebpack-dev -server/is sues/887). | |
1085 | ||
1086 | This shoul dn’t aff ect you wh en develop ing on `lo calhost`, but if you develop r emotely li ke [descri bed here]( https://gi thub.com/f acebookinc ubator/cre ate-react- app/issues /2271), yo u will see this erro r in the b rowser aft er enablin g the `pro xy` option : | |
1087 | ||
1088 | >Invalid H ost header | |
1089 | ||
1090 | To work ar ound it, y ou can spe cify your public dev elopment h ost in a f ile called `.env.dev elopment` in the roo t of your project: | |
1091 | ||
1092 | ``` | |
1093 | HOST=mypub licdevhost .com | |
1094 | ``` | |
1095 | ||
1096 | If you res tart the d evelopment server no w and load the app f rom the sp ecified ho st, it sho uld work. | |
1097 | ||
1098 | If you are still hav ing issues or if you ’re usin g a more e xotic envi ronment li ke a cloud editor, y ou can byp ass the ho st check c ompletely by adding a line to `.env.deve lopment.lo cal`. **No te that th is is dang erous and exposes yo ur machine to remote code exec ution from malicious websites: ** | |
1099 | ||
1100 | ``` | |
1101 | # NOTE: TH IS IS DANG EROUS! | |
1102 | # It expos es your ma chine to a ttacks fro m the webs ites you v isit. | |
1103 | DANGEROUSL Y_DISABLE_ HOST_CHECK =true | |
1104 | ``` | |
1105 | ||
1106 | We don’t recommend this appr oach. | |
1107 | ||
1108 | ### Config uring the Proxy Manu ally | |
1109 | ||
1110 | >Note: thi s feature is availab le with `r eact-scrip ts@1.0.0` and higher . | |
1111 | ||
1112 | If the `pr oxy` optio n is **not ** flexibl e enough f or you, yo u can spec ify an obj ect in the following form (in `package.j son`).<br> | |
1113 | You may al so specify any confi guration v alue [`htt p-proxy-mi ddleware`] (https://g ithub.com/ chimurai/h ttp-proxy- middleware #options) or [`http- proxy`](ht tps://gith ub.com/nod ejitsu/nod e-http-pro xy#options ) supports . | |
1114 | ```js | |
1115 | { | |
1116 | // ... | |
1117 | "proxy": { | |
1118 | "/api" : { | |
1119 | "tar get": "<ur l>", | |
1120 | "ws" : true | |
1121 | // . .. | |
1122 | } | |
1123 | } | |
1124 | // ... | |
1125 | } | |
1126 | ``` | |
1127 | ||
1128 | All reques ts matchin g this pat h will be proxies, n o exceptio ns. This i ncludes re quests for `text/htm l`, which the standa rd `proxy` option do es not pro xy. | |
1129 | ||
1130 | If you nee d to speci fy multipl e proxies, you may d o so by sp ecifying a dditional entries. | |
1131 | Matches ar e regular expression s, so that you can u se a regex p to match multiple paths. | |
1132 | ```js | |
1133 | { | |
1134 | // ... | |
1135 | "proxy": { | |
1136 | // Mat ches any r equest sta rting with /api | |
1137 | "/api" : { | |
1138 | "tar get": "<ur l_1>", | |
1139 | "ws" : true | |
1140 | // . .. | |
1141 | }, | |
1142 | // Mat ches any r equest sta rting with /foo | |
1143 | "/foo" : { | |
1144 | "tar get": "<ur l_2>", | |
1145 | "ssl ": true, | |
1146 | "pat hRewrite": { | |
1147 | "^ /foo": "/f oo/beta" | |
1148 | } | |
1149 | // . .. | |
1150 | }, | |
1151 | // Mat ches /bar/ abc.html b ut not /ba r/sub/def. html | |
1152 | "/bar/ [^/]*[.]ht ml": { | |
1153 | "tar get": "<ur l_3>", | |
1154 | // . .. | |
1155 | }, | |
1156 | // Mat ches /baz/ abc.html a nd /baz/su b/def.html | |
1157 | "/baz/ .*/.*[.]ht ml": { | |
1158 | "tar get": "<ur l_4>" | |
1159 | // . .. | |
1160 | } | |
1161 | } | |
1162 | // ... | |
1163 | } | |
1164 | ``` | |
1165 | ||
1166 | ### Config uring a We bSocket Pr oxy | |
1167 | ||
1168 | When setti ng up a We bSocket pr oxy, there are a som e extra co nsideratio ns to be a ware of. | |
1169 | ||
1170 | If you’r e using a WebSocket engine lik e [Socket. io](https: //socket.i o/), you m ust have a Socket.io server ru nning that you can u se as the proxy targ et. Socket .io will n ot work wi th a stand ard WebSoc ket server . Specific ally, don' t expect S ocket.io t o work wit h [the web socket.org echo test ](http://w ebsocket.o rg/echo.ht ml). | |
1171 | ||
1172 | There’s some good documentat ion availa ble for [s etting up a Socket.i o server]( https://so cket.io/do cs/). | |
1173 | ||
1174 | Standard W ebSockets **will** w ork with a standard WebSocket server as well as th e websocke t.org echo test. You can use l ibraries l ike [ws](h ttps://git hub.com/we bsockets/w s) for the server, w ith [nativ e WebSocke ts in the browser](h ttps://dev eloper.moz illa.org/e n-US/docs/ Web/API/We bSocket). | |
1175 | ||
1176 | Either way , you can proxy WebS ocket requ ests manua lly in `pa ckage.json `: | |
1177 | ||
1178 | ```js | |
1179 | { | |
1180 | // ... | |
1181 | "proxy": { | |
1182 | "/sock et": { | |
1183 | // Y our compat ible WebSo cket serve r | |
1184 | "tar get": "ws: //<socket_ url>", | |
1185 | // T ell http-p roxy-middl eware that this is a WebSocket proxy. | |
1186 | // A lso allows you to pr oxy WebSoc ket reques ts without an additi onal HTTP request | |
1187 | // h ttps://git hub.com/ch imurai/htt p-proxy-mi ddleware#e xternal-we bsocket-up grade | |
1188 | "ws" : true | |
1189 | // . .. | |
1190 | } | |
1191 | } | |
1192 | // ... | |
1193 | } | |
1194 | ``` | |
1195 | ||
1196 | ## Using H TTPS in De velopment | |
1197 | ||
1198 | >Note: thi s feature is availab le with `r eact-scrip ts@0.4.0` and higher . | |
1199 | ||
1200 | You may re quire the dev server to serve pages over HTTPS. On e particul ar case wh ere this c ould be us eful is wh en using [ the "proxy " feature] (#proxying -api-reque sts-in-dev elopment) to proxy r equests to an API se rver when that API s erver is i tself serv ing HTTPS. | |
1201 | ||
1202 | To do this , set the `HTTPS` en vironment variable t o `true`, then start the dev s erver as u sual with `npm start `: | |
1203 | ||
1204 | #### Windo ws (cmd.ex e) | |
1205 | ||
1206 | ```cmd | |
1207 | set HTTPS= true&&npm start | |
1208 | ``` | |
1209 | ||
1210 | #### Windo ws (Powers hell) | |
1211 | ||
1212 | ```Powersh ell | |
1213 | ($env:HTTP S = $true) -and (npm start) | |
1214 | ``` | |
1215 | ||
1216 | (Note: the lack of w hitespace is intenti onal.) | |
1217 | ||
1218 | #### Linux , macOS (B ash) | |
1219 | ||
1220 | ```bash | |
1221 | HTTPS=true npm start | |
1222 | ``` | |
1223 | ||
1224 | Note that the server will use a self-sig ned certif icate, so your web b rowser wil l almost d efinitely display a warning up on accessi ng the pag e. | |
1225 | ||
1226 | ## Generat ing Dynami c `<meta>` Tags on t he Server | |
1227 | ||
1228 | Since Crea te React A pp doesn†™t support server re ndering, y ou might b e wonderin g how to m ake `<meta >` tags dy namic and reflect th e current URL. To so lve this, we recomme nd to add placeholde rs into th e HTML, li ke this: | |
1229 | ||
1230 | ```html | |
1231 | <!doctype html> | |
1232 | <html lang ="en"> | |
1233 | <head> | |
1234 | <meta property=" og:title" content="_ _OG_TITLE_ _"> | |
1235 | <meta property=" og:descrip tion" cont ent="__OG_ DESCRIPTIO N__"> | |
1236 | ``` | |
1237 | ||
1238 | Then, on t he server, regardles s of the b ackend you use, you can read ` index.html ` into mem ory and re place `__O G_TITLE__` , `__OG_DE SCRIPTION_ _`, and an y other pl aceholders with valu es dependi ng on the current UR L. Just ma ke sure to sanitize and escape the inter polated va lues so th at they ar e safe to embed into HTML! | |
1239 | ||
1240 | If you use a Node se rver, you can even s hare the r oute match ing logic between th e client a nd the ser ver. Howev er duplica ting it al so works f ine in sim ple cases. | |
1241 | ||
1242 | ## Pre-Ren dering int o Static H TML Files | |
1243 | ||
1244 | If you’r e hosting your `buil d` with a static hos ting provi der you ca n use [rea ct-snapsho t](https:/ /www.npmjs .com/packa ge/react-s napshot) o r [react-s nap](https ://github. com/stereo booster/re act-snap) to generat e HTML pag es for eac h route, o r relative link, in your appli cation. Th ese pages will then seamlessly become ac tive, or â €œhydrated â€, when the JavaSc ript bundl e has load ed. | |
1245 | ||
1246 | There are also oppor tunities t o use this outside o f static h osting, to take the pressure o ff the ser ver when g enerating and cachin g routes. | |
1247 | ||
1248 | The primar y benefit of pre-ren dering is that you g et the cor e content of each pa ge _with_ the HTML p ayload—r egardless of whether or not yo ur JavaScr ipt bundle successfu lly downlo ads. It al so increas es the lik elihood th at each ro ute of you r applicat ion will b e picked u p by searc h engines. | |
1249 | ||
1250 | You can re ad more ab out [zero- configurat ion pre-re ndering (a lso called snapshott ing) here] (https://m edium.com/ superhighf ives/an-al most-stati c-stack-6d f0a2791319 ). | |
1251 | ||
1252 | ## Injecti ng Data fr om the Ser ver into t he Page | |
1253 | ||
1254 | Similarly to the pre vious sect ion, you c an leave s ome placeh olders in the HTML t hat inject global va riables, f or example : | |
1255 | ||
1256 | ```js | |
1257 | <!doctype html> | |
1258 | <html lang ="en"> | |
1259 | <head> | |
1260 | <scrip t> | |
1261 | wind ow.SERVER_ DATA = __S ERVER_DATA __; | |
1262 | </scri pt> | |
1263 | ``` | |
1264 | ||
1265 | Then, on t he server, you can r eplace `__ SERVER_DAT A__` with a JSON of real data right befo re sending the respo nse. The c lient code can then read `wind ow.SERVER_ DATA` to u se it. **M ake sure t o [sanitiz e the JSON before se nding it t o the clie nt](https: //medium.c om/node-se curity/the -most-comm on-xss-vul nerability -in-react- js-applica tions-2bdf fbcc1fa0) as it make s your app vulnerabl e to XSS a ttacks.** | |
1266 | ||
1267 | ## Running Tests | |
1268 | ||
1269 | >Note: thi s feature is availab le with `r eact-scrip ts@0.3.0` and higher .<br> | |
1270 | >[Read the migration guide to learn how to enable it in olde r projects !](https:/ /github.co m/facebook incubator/ create-rea ct-app/blo b/master/C HANGELOG.m d#migratin g-from-023 -to-030) | |
1271 | ||
1272 | Create Rea ct App use s [Jest](h ttps://fac ebook.gith ub.io/jest /) as its test runne r. To prep are for th is integra tion, we d id a [majo r revamp]( https://fa cebook.git hub.io/jes t/blog/201 6/09/01/je st-15.html ) of Jest so if you heard bad things abo ut it year s ago, giv e it anoth er try. | |
1273 | ||
1274 | Jest is a Node-based runner. T his means that the t ests alway s run in a Node envi ronment an d not in a real brow ser. This lets us en able fast iteration speed and prevent fl akiness. | |
1275 | ||
1276 | While Jest provides browser gl obals such as `windo w` thanks to [jsdom] (https://g ithub.com/ tmpvar/jsd om), they are only a pproximati ons of the real brow ser behavi or. Jest i s intended to be use d for unit tests of your logic and your components rather th an the DOM quirks. | |
1277 | ||
1278 | We recomme nd that yo u use a se parate too l for brow ser end-to -end tests if you ne ed them. T hey are be yond the s cope of Cr eate React App. | |
1279 | ||
1280 | ### Filena me Convent ions | |
1281 | ||
1282 | Jest will look for t est files with any o f the foll owing popu lar naming conventio ns: | |
1283 | ||
1284 | * Files wi th `.js` s uffix in ` __tests__` folders. | |
1285 | * Files wi th `.test. js` suffix . | |
1286 | * Files wi th `.spec. js` suffix . | |
1287 | ||
1288 | The `.test .js` / `.s pec.js` fi les (or th e `__tests __` folder s) can be located at any depth under the `src` top level fol der. | |
1289 | ||
1290 | We recomme nd to put the test f iles (or ` __tests__` folders) next to th e code the y are test ing so tha t relative imports a ppear shor ter. For e xample, if `App.test .js` and ` App.js` ar e in the s ame folder , the test just need s to `impo rt App fro m './App'` instead o f a long r elative pa th. Coloca tion also helps find tests mor e quickly in larger projects. | |
1291 | ||
1292 | ### Comman d Line Int erface | |
1293 | ||
1294 | When you r un `npm te st`, Jest will launc h in the w atch mode. Every tim e you save a file, i t will re- run the te sts, just like `npm start` rec ompiles th e code. | |
1295 | ||
1296 | The watche r includes an intera ctive comm and-line i nterface w ith the ab ility to r un all tes ts, or foc us on a se arch patte rn. It is designed t his way so that you can keep i t open and enjoy fas t re-runs. You can l earn the c ommands fr om the “ Watch Usag e†note that the w atcher pri nts after every run: | |
1297 | ||
1298 |  | |
1299 | ||
1300 | ### Versio n Control Integratio n | |
1301 | ||
1302 | By default , when you run `npm test`, Jes t will onl y run the tests rela ted to fil es changed since the last comm it. This i s an optim ization de signed to make your tests run fast regar dless of h ow many te sts you ha ve. Howeve r it assum es that yo u don’t often comm it the cod e that doe sn’t pas s the test s. | |
1303 | ||
1304 | Jest will always exp licitly me ntion that it only r an tests r elated to the files changed si nce the la st commit. You can a lso press `a` in the watch mod e to force Jest to r un all tes ts. | |
1305 | ||
1306 | Jest will always run all tests on a [con tinuous in tegration] (#continuo us-integra tion) serv er or if t he project is not in side a Git or Mercur ial reposi tory. | |
1307 | ||
1308 | ### Writin g Tests | |
1309 | ||
1310 | To create tests, add `it()` (o r `test()` ) blocks w ith the na me of the test and i ts code. Y ou may opt ionally wr ap them in `describe ()` blocks for logic al groupin g but this is neithe r required nor recom mended. | |
1311 | ||
1312 | Jest provi des a buil t-in `expe ct()` glob al functio n for maki ng asserti ons. A bas ic test co uld look l ike this: | |
1313 | ||
1314 | ```js | |
1315 | import sum from './s um'; | |
1316 | ||
1317 | it('sums n umbers', ( ) => { | |
1318 | expect(s um(1, 2)). toEqual(3) ; | |
1319 | expect(s um(2, 2)). toEqual(4) ; | |
1320 | }); | |
1321 | ``` | |
1322 | ||
1323 | All `expec t()` match ers suppor ted by Jes t are [ext ensively d ocumented here](http s://facebo ok.github. io/jest/do cs/en/expe ct.html#co ntent).<br > | |
1324 | You can al so use [`j est.fn()` and `expec t(fn).toBe Called()`] (https://f acebook.gi thub.io/je st/docs/en /expect.ht ml#tohaveb eencalled) to create “spies⠀ or mock functions . | |
1325 | ||
1326 | ### Testin g Componen ts | |
1327 | ||
1328 | There is a broad spe ctrum of c omponent t esting tec hniques. T hey range from a “ smoke test †verify ing that a component renders w ithout thr owing, to shallow re ndering an d testing some of th e output, to full re ndering an d testing component lifecycle and state changes. | |
1329 | ||
1330 | Different projects c hoose diff erent test ing tradeo ffs based on how oft en compone nts change , and how much logic they cont ain. If yo u haven’ t decided on a testi ng strateg y yet, we recommend that you s tart with creating s imple smok e tests fo r your com ponents: | |
1331 | ||
1332 | ```js | |
1333 | import Rea ct from 'r eact'; | |
1334 | import Rea ctDOM from 'react-do m'; | |
1335 | import App from './A pp'; | |
1336 | ||
1337 | it('render s without crashing', () => { | |
1338 | const di v = docume nt.createE lement('di v'); | |
1339 | ReactDOM .render(<A pp />, div ); | |
1340 | }); | |
1341 | ``` | |
1342 | ||
1343 | This test mounts a c omponent a nd makes s ure that i t didn’t throw dur ing render ing. Tests like this provide a lot of va lue with v ery little effort so they are great as a starting point, and this is t he test yo u will fin d in `src/ App.test.j s`. | |
1344 | ||
1345 | When you e ncounter b ugs caused by changi ng compone nts, you w ill gain a deeper in sight into which par ts of them are worth testing i n your app lication. This might be a good time to i ntroduce m ore specif ic tests a sserting s pecific ex pected out put or beh avior. | |
1346 | ||
1347 | If you’d like to t est compon ents in is olation fr om the chi ld compone nts they r ender, we recommend using [`sh allow()` r endering A PI](http:/ /airbnb.io /enzyme/do cs/api/sha llow.html) from [Enz yme](http: //airbnb.i o/enzyme/) . To insta ll it, run : | |
1348 | ||
1349 | ```sh | |
1350 | npm instal l --save e nzyme enzy me-adapter -react-16 react-test -renderer | |
1351 | ``` | |
1352 | ||
1353 | Alternativ ely you ma y use `yar n`: | |
1354 | ||
1355 | ```sh | |
1356 | yarn add e nzyme enzy me-adapter -react-16 react-test -renderer | |
1357 | ``` | |
1358 | ||
1359 | As of Enzy me 3, you will need to install Enzyme al ong with a n Adapter correspond ing to the version o f React yo u are usin g. (The ex amples abo ve use the adapter f or React 1 6.) | |
1360 | ||
1361 | The adapte r will als o need to be configu red in you r [global setup file ](#initial izing-test -environme nt): | |
1362 | ||
1363 | #### `src/ setupTests .js` | |
1364 | ```js | |
1365 | import { c onfigure } from 'enz yme'; | |
1366 | import Ada pter from 'enzyme-ad apter-reac t-16'; | |
1367 | ||
1368 | configure( { adapter: new Adapt er() }); | |
1369 | ``` | |
1370 | ||
1371 | >Note: Kee p in mind that if yo u decide t o "eject" before cre ating `src /setupTest s.js`, the resulting `package. json` file won't con tain any r eference t o it. [Rea d here](#i nitializin g-test-env ironment) to learn h ow to add this after ejecting. | |
1372 | ||
1373 | Now you ca n write a smoke test with it: | |
1374 | ||
1375 | ```js | |
1376 | import Rea ct from 'r eact'; | |
1377 | import { s hallow } f rom 'enzym e'; | |
1378 | import App from './A pp'; | |
1379 | ||
1380 | it('render s without crashing', () => { | |
1381 | shallow( <App />); | |
1382 | }); | |
1383 | ``` | |
1384 | ||
1385 | Unlike the previous smoke test using `Re actDOM.ren der()`, th is test on ly renders `<App>` a nd doesn†™t go deep er. For ex ample, eve n if `<App >` itself renders a `<Button>` that thro ws, this t est will p ass. Shall ow renderi ng is grea t for isol ated unit tests, but you may s till want to create some full rendering tests to e nsure the components integrate correctly . Enzyme s upports [f ull render ing with ` mount()`]( http://air bnb.io/enz yme/docs/a pi/mount.h tml), and you can al so use it for testin g state ch anges and component lifecycle. | |
1386 | ||
1387 | You can re ad the [En zyme docum entation]( http://air bnb.io/enz yme/) for more testi ng techniq ues. Enzym e document ation uses Chai and Sinon for assertions but you d on’t hav e to use t hem becaus e Jest pro vides buil t-in `expe ct()` and `jest.fn() ` for spie s. | |
1388 | ||
1389 | Here is an example f rom Enzyme documenta tion that asserts sp ecific out put, rewri tten to us e Jest mat chers: | |
1390 | ||
1391 | ```js | |
1392 | import Rea ct from 'r eact'; | |
1393 | import { s hallow } f rom 'enzym e'; | |
1394 | import App from './A pp'; | |
1395 | ||
1396 | it('render s welcome message', () => { | |
1397 | const wr apper = sh allow(<App />); | |
1398 | const we lcome = <h 2>Welcome to React</ h2>; | |
1399 | // expec t(wrapper. contains(w elcome)).t o.equal(tr ue); | |
1400 | expect(w rapper.con tains(welc ome)).toEq ual(true); | |
1401 | }); | |
1402 | ``` | |
1403 | ||
1404 | All Jest m atchers ar e [extensi vely docum ented here ](http://f acebook.gi thub.io/je st/docs/en /expect.ht ml).<br> | |
1405 | Neverthele ss you can use a thi rd-party a ssertion l ibrary lik e [Chai](h ttp://chai js.com/) i f you want to, as de scribed be low. | |
1406 | ||
1407 | Additional ly, you mi ght find [ jest-enzym e](https:/ /github.co m/blaineka sten/enzym e-matchers ) helpful to simplif y your tes ts with re adable mat chers. The above `co ntains` co de can be written mo re simply with jest- enzyme. | |
1408 | ||
1409 | ```js | |
1410 | expect(wra pper).toCo ntainReact (welcome) | |
1411 | ``` | |
1412 | ||
1413 | To enable this, inst all `jest- enzyme`: | |
1414 | ||
1415 | ```sh | |
1416 | npm instal l --save j est-enzyme | |
1417 | ``` | |
1418 | ||
1419 | Alternativ ely you ma y use `yar n`: | |
1420 | ||
1421 | ```sh | |
1422 | yarn add j est-enzyme | |
1423 | ``` | |
1424 | ||
1425 | Import it in [`src/s etupTests. js`](#init ializing-t est-enviro nment) to make its m atchers av ailable in every tes t: | |
1426 | ||
1427 | ```js | |
1428 | import 'je st-enzyme' ; | |
1429 | ``` | |
1430 | ||
1431 | ### Using Third Part y Assertio n Librarie s | |
1432 | ||
1433 | We recomme nd that yo u use `exp ect()` for assertion s and `jes t.fn()` fo r spies. I f you are having iss ues with t hem please [file tho se against Jest](htt ps://githu b.com/face book/jest/ issues/new ), and weâ €™ll fix t hem. We in tend to ke ep making them bette r for Reac t, support ing, for e xample, [p retty-prin ting React elements as JSX](ht tps://gith ub.com/fac ebook/jest /pull/1566 ). | |
1434 | ||
1435 | However, i f you are used to ot her librar ies, such as [Chai]( http://cha ijs.com/) and [Sinon ](http://s inonjs.org /), or if you have e xisting co de using t hem that y ou’d lik e to port over, you can import them norm ally like this: | |
1436 | ||
1437 | ```js | |
1438 | import sin on from 's inon'; | |
1439 | import { e xpect } fr om 'chai'; | |
1440 | ``` | |
1441 | ||
1442 | and then u se them in your test s like you normally do. | |
1443 | ||
1444 | ### Initia lizing Tes t Environm ent | |
1445 | ||
1446 | >Note: thi s feature is availab le with `r eact-scrip ts@0.4.0` and higher . | |
1447 | ||
1448 | If your ap p uses a b rowser API that you need to mo ck in your tests or if you jus t need a g lobal setu p before r unning you r tests, a dd a `src/ setupTests .js` to yo ur project . It will be automat ically exe cuted befo re running your test s. | |
1449 | ||
1450 | For exampl e: | |
1451 | ||
1452 | #### `src/ setupTests .js` | |
1453 | ```js | |
1454 | const loca lStorageMo ck = { | |
1455 | getItem: jest.fn() , | |
1456 | setItem: jest.fn() , | |
1457 | clear: j est.fn() | |
1458 | }; | |
1459 | global.loc alStorage = localSto rageMock | |
1460 | ``` | |
1461 | ||
1462 | >Note: Kee p in mind that if yo u decide t o "eject" before cre ating `src /setupTest s.js`, the resulting `package. json` file won't con tain any r eference t o it, so y ou should manually c reate the property ` setupTestF rameworkSc riptFile` in the con figuration for Jest, something like the following: | |
1463 | ||
1464 | >```js | |
1465 | >"jest": { | |
1466 | > // ... | |
1467 | > "setup TestFramew orkScriptF ile": "<ro otDir>/src /setupTest s.js" | |
1468 | > } | |
1469 | > ``` | |
1470 | ||
1471 | ### Focusi ng and Exc luding Tes ts | |
1472 | ||
1473 | You can re place `it( )` with `x it()` to t emporarily exclude a test from being exe cuted.<br> | |
1474 | Similarly, `fit()` l ets you fo cus on a s pecific te st without running a ny other t ests. | |
1475 | ||
1476 | ### Covera ge Reporti ng | |
1477 | ||
1478 | Jest has a n integrat ed coverag e reporter that work s well wit h ES6 and requires n o configur ation.<br> | |
1479 | Run `npm t est -- --c overage` ( note extra `--` in t he middle) to includ e a covera ge report like this: | |
1480 | ||
1481 |  | |
1482 | ||
1483 | Note that tests run much slowe r with cov erage so i t is recom mended to run it sep arately fr om your no rmal workf low. | |
1484 | ||
1485 | #### Confi guration | |
1486 | ||
1487 | The defaul t Jest cov erage conf iguration can be ove rriden by adding any of the fo llowing su pported ke ys to a Je st config in your pa ckage.json . | |
1488 | ||
1489 | Supported overrides: | |
1490 | - [`colle ctCoverage From`](htt ps://faceb ook.github .io/jest/d ocs/en/con figuration .html#coll ectcoverag efrom-arra y) | |
1491 | - [`cover ageReporte rs`](https ://faceboo k.github.i o/jest/doc s/en/confi guration.h tml#covera gereporter s-array-st ring) | |
1492 | - [`cover ageThresho ld`](https ://faceboo k.github.i o/jest/doc s/en/confi guration.h tml#covera gethreshol d-object) | |
1493 | - [`snaps hotSeriali zers`](htt ps://faceb ook.github .io/jest/d ocs/en/con figuration .html#snap shotserial izers-arra y-string) | |
1494 | ||
1495 | Example pa ckage.json : | |
1496 | ||
1497 | ```json | |
1498 | { | |
1499 | "name": "your-pack age", | |
1500 | "jest": { | |
1501 | "colle ctCoverage From" : [ | |
1502 | "src /**/*.{js, jsx}", | |
1503 | "!<r ootDir>/no de_modules /", | |
1504 | "!<r ootDir>/pa th/to/dir/ " | |
1505 | ], | |
1506 | "cover ageThresho ld": { | |
1507 | "glo bal": { | |
1508 | "b ranches": 90, | |
1509 | "f unctions": 90, | |
1510 | "l ines": 90, | |
1511 | "s tatements" : 90 | |
1512 | } | |
1513 | }, | |
1514 | "cover ageReporte rs": ["tex t"], | |
1515 | "snaps hotSeriali zers": ["m y-serializ er-module" ] | |
1516 | } | |
1517 | } | |
1518 | ``` | |
1519 | ||
1520 | ### Contin uous Integ ration | |
1521 | ||
1522 | By default `npm test ` runs the watcher w ith intera ctive CLI. However, you can fo rce it to run tests once and f inish the process by setting a n environm ent variab le called `CI`. | |
1523 | ||
1524 | When creat ing a buil d of your applicatio n with `np m run buil d` linter warnings a re not che cked by de fault. Lik e `npm tes t`, you ca n force th e build to perform a linter wa rning chec k by setti ng the env ironment v ariable `C I`. If any warnings are encoun tered then the build fails. | |
1525 | ||
1526 | Popular CI servers a lready set the envir onment var iable `CI` by defaul t but you can do thi s yourself too: | |
1527 | ||
1528 | ### On CI servers | |
1529 | #### Travi s CI | |
1530 | ||
1531 | 1. Followi ng the [Tr avis Getti ng started ](https:// docs.travi s-ci.com/u ser/gettin g-started/ ) guide fo r syncing your GitHu b reposito ry with Tr avis. You may need to initial ize some s ettings ma nually in your [prof ile](https ://travis- ci.org/pro file) page . | |
1532 | 1. Add a ` .travis.ym l` file to your git repository . | |
1533 | ``` | |
1534 | language: node_js | |
1535 | node_js: | |
1536 | - 6 | |
1537 | cache: | |
1538 | director ies: | |
1539 | - node _modules | |
1540 | script: | |
1541 | - npm ru n build | |
1542 | - npm te st | |
1543 | ``` | |
1544 | 1. Trigger your firs t build wi th a git p ush. | |
1545 | 1. [Custom ize your T ravis CI B uild](http s://docs.t ravis-ci.c om/user/cu stomizing- the-build/ ) if neede d. | |
1546 | ||
1547 | #### Circl eCI | |
1548 | ||
1549 | Follow [th is article ](https:// medium.com /@knowbody /circleci- and-zeits- now-sh-c9b 7eebcd3c1) to set up CircleCI with a Cre ate React App projec t. | |
1550 | ||
1551 | ### On you r own envi ronment | |
1552 | ##### Wind ows (cmd.e xe) | |
1553 | ||
1554 | ```cmd | |
1555 | set CI=tru e&&npm tes t | |
1556 | ``` | |
1557 | ||
1558 | ```cmd | |
1559 | set CI=tru e&&npm run build | |
1560 | ``` | |
1561 | ||
1562 | (Note: the lack of w hitespace is intenti onal.) | |
1563 | ||
1564 | ##### Wind ows (Power shell) | |
1565 | ||
1566 | ```Powersh ell | |
1567 | ($env:CI = $true) -a nd (npm te st) | |
1568 | ``` | |
1569 | ||
1570 | ```Powersh ell | |
1571 | ($env:CI = $true) -a nd (npm ru n build) | |
1572 | ``` | |
1573 | ||
1574 | ##### Linu x, macOS ( Bash) | |
1575 | ||
1576 | ```bash | |
1577 | CI=true np m test | |
1578 | ``` | |
1579 | ||
1580 | ```bash | |
1581 | CI=true np m run buil d | |
1582 | ``` | |
1583 | ||
1584 | The test c ommand wil l force Je st to run tests once instead o f launchin g the watc her. | |
1585 | ||
1586 | > If you find yours elf doing this often in develo pment, ple ase [file an issue]( https://gi thub.com/f acebookinc ubator/cre ate-react- app/issues /new) to t ell us abo ut your us e case bec ause we wa nt to make watcher t he best ex perience a nd are ope n to chang ing how it works to accommodat e more wor kflows. | |
1587 | ||
1588 | The build command wi ll check f or linter warnings a nd fail if any are f ound. | |
1589 | ||
1590 | ### Disabl ing jsdom | |
1591 | ||
1592 | By default , the `pac kage.json` of the ge nerated pr oject look s like thi s: | |
1593 | ||
1594 | ```js | |
1595 | "scripts ": { | |
1596 | "start ": "react- scripts st art", | |
1597 | "build ": "react- scripts bu ild", | |
1598 | "test" : "react-s cripts tes t --env=js dom" | |
1599 | ``` | |
1600 | ||
1601 | If you kno w that non e of your tests depe nd on [jsd om](https: //github.c om/tmpvar/ jsdom), yo u can safe ly remove `--env=jsd om`, and y our tests will run f aster: | |
1602 | ||
1603 | ```diff | |
1604 | "scripts ": { | |
1605 | "start ": "react- scripts st art", | |
1606 | "build ": "react- scripts bu ild", | |
1607 | - "test" : "react-s cripts tes t --env=js dom" | |
1608 | + "test" : "react-s cripts tes t" | |
1609 | ``` | |
1610 | ||
1611 | To help yo u make up your mind, here is a list of A PIs that * *need jsdo m**: | |
1612 | ||
1613 | * Any brow ser global s like `wi ndow` and `document` | |
1614 | * [`ReactD OM.render( )`](https: //facebook .github.io /react/doc s/top-leve l-api.html #reactdom. render) | |
1615 | * [`TestUt ils.render IntoDocume nt()`](htt ps://faceb ook.github .io/react/ docs/test- utils.html #renderint odocument) ([a short cut](https ://github. com/facebo ok/react/b lob/34761c f9a252964a bfaab6faf7 4d473ad95d 1f21/src/t est/ReactT estUtils.j s#L83-L91) for the a bove) | |
1616 | * [`mount( )`](http:/ /airbnb.io /enzyme/do cs/api/mou nt.html) i n [Enzyme] (http://ai rbnb.io/en zyme/index .html) | |
1617 | ||
1618 | In contras t, **jsdom is not ne eded** for the follo wing APIs: | |
1619 | ||
1620 | * [`TestUt ils.create Renderer() `](https:/ /facebook. github.io/ react/docs /test-util s.html#sha llow-rende ring) (sha llow rende ring) | |
1621 | * [`shallo w()`](http ://airbnb. io/enzyme/ docs/api/s hallow.htm l) in [Enz yme](http: //airbnb.i o/enzyme/i ndex.html) | |
1622 | ||
1623 | Finally, j sdom is al so not nee ded for [s napshot te sting](htt p://facebo ok.github. io/jest/bl og/2016/07 /27/jest-1 4.html). | |
1624 | ||
1625 | ### Snapsh ot Testing | |
1626 | ||
1627 | Snapshot t esting is a feature of Jest th at automat ically gen erates tex t snapshot s of your components and saves them on t he disk so if the UI output ch anges, you get notif ied withou t manually writing a ny asserti ons on the component output. [ Read more about snap shot testi ng.](http: //facebook .github.io /jest/blog /2016/07/2 7/jest-14. html) | |
1628 | ||
1629 | ### Editor Integrati on | |
1630 | ||
1631 | If you use [Visual S tudio Code ](https:// code.visua lstudio.co m), there is a [Jest extension ](https:// github.com /orta/vsco de-jest) w hich works with Crea te React A pp out of the box. T his provid es a lot o f IDE-like features while usin g a text e ditor: sho wing the s tatus of a test run with poten tial fail messages i nline, sta rting and stopping t he watcher automatic ally, and offering o ne-click s napshot up dates. | |
1632 | ||
1633 |  | |
1634 | ||
1635 | ## Debuggi ng Tests | |
1636 | ||
1637 | There are various wa ys to setu p a debugg er for you r Jest tes ts. We cov er debuggi ng in Chro me and [Vi sual Studi o Code](ht tps://code .visualstu dio.com/). | |
1638 | ||
1639 | >Note: deb ugging tes ts require s Node 8 o r higher. | |
1640 | ||
1641 | ### Debugg ing Tests in Chrome | |
1642 | ||
1643 | Add the fo llowing to the `scri pts` secti on in your project's `package. json` | |
1644 | ```json | |
1645 | "scripts": { | |
1646 | "test: debug": "r eact-scrip ts --inspe ct-brk tes t --runInB and --env= jsdom" | |
1647 | } | |
1648 | ``` | |
1649 | Place `deb ugger;` st atements i n any test and run: | |
1650 | ```bash | |
1651 | $ npm run test:debug | |
1652 | ``` | |
1653 | ||
1654 | This will start runn ing your J est tests, but pause before ex ecuting to allow a d ebugger to attach to the proce ss. | |
1655 | ||
1656 | Open the f ollowing i n Chrome | |
1657 | ``` | |
1658 | about:insp ect | |
1659 | ``` | |
1660 | ||
1661 | After open ing that l ink, the C hrome Deve loper Tool s will be displayed. Select `i nspect` on your proc ess and a breakpoint will be s et at the first line of the re act script (this is done simpl y to give you time t o open the developer tools and to preven t Jest fro m executin g before y ou have ti me to do s o). Click the button that look s like a " play" butt on in the upper righ t hand sid e of the s creen to c ontinue ex ecution. W hen Jest e xecutes th e test tha t contains the debug ger statem ent, execu tion will pause and you can ex amine the current sc ope and ca ll stack. | |
1662 | ||
1663 | >Note: the --runInBa nd cli opt ion makes sure Jest runs test in the sam e process rather tha n spawning processes for indiv idual test s. Normall y Jest par allelizes test runs across pro cesses but it is har d to debug many proc esses at t he same ti me. | |
1664 | ||
1665 | ### Debugg ing Tests in Visual Studio Cod e | |
1666 | ||
1667 | Debugging Jest tests is suppor ted out of the box f or [Visual Studio Co de](https: //code.vis ualstudio. com). | |
1668 | ||
1669 | Use the fo llowing [` launch.jso n`](https: //code.vis ualstudio. com/docs/e ditor/debu gging#_lau nch-config urations) configurat ion file: | |
1670 | ``` | |
1671 | { | |
1672 | "version ": "0.2.0" , | |
1673 | "configu rations": [ | |
1674 | { | |
1675 | "nam e": "Debug CRA Tests ", | |
1676 | "typ e": "node" , | |
1677 | "req uest": "la unch", | |
1678 | "run timeExecut able": "${ workspaceR oot}/node_ modules/.b in/react-s cripts", | |
1679 | "arg s": [ | |
1680 | "t est", | |
1681 | "- -runInBand ", | |
1682 | "- -no-cache" , | |
1683 | "- -env=jsdom " | |
1684 | ], | |
1685 | "cwd ": "${work spaceRoot} ", | |
1686 | "pro tocol": "i nspector", | |
1687 | "con sole": "in tegratedTe rminal", | |
1688 | "int ernalConso leOptions" : "neverOp en" | |
1689 | } | |
1690 | ] | |
1691 | } | |
1692 | ``` | |
1693 | ||
1694 | ## Develop ing Compon ents in Is olation | |
1695 | ||
1696 | Usually, i n an app, you have a lot of UI component s, and eac h of them has many d ifferent s tates. | |
1697 | For an exa mple, a si mple butto n componen t could ha ve followi ng states: | |
1698 | ||
1699 | * In a reg ular state , with a t ext label. | |
1700 | * In the d isabled mo de. | |
1701 | * In a loa ding state . | |
1702 | ||
1703 | Usually, i t’s hard to see th ese states without r unning a s ample app or some ex amples. | |
1704 | ||
1705 | Create Rea ct App doe sn’t inc lude any t ools for t his by def ault, but you can ea sily add [ Storybook for React] (https://s torybook.j s.org) ([s ource](htt ps://githu b.com/stor ybooks/sto rybook)) o r [React S tyleguidis t](https:/ /react-sty leguidist. js.org/) ( [source](h ttps://git hub.com/st yleguidist /react-sty leguidist) ) to your project. * *These are third-par ty tools t hat let yo u develop components and see a ll their s tates in i solation f rom your a pp**. | |
1706 | ||
1707 |  | |
1708 | ||
1709 | You can al so deploy your Story book or st yle guide as a stati c app. Thi s way, eve ryone in y our team c an view an d review d ifferent s tates of U I componen ts without starting a backend server or creating a n account in your ap p. | |
1710 | ||
1711 | ### Gettin g Started with Story book | |
1712 | ||
1713 | Storybook is a devel opment env ironment f or React U I componen ts. It all ows you to browse a component library, v iew the di fferent st ates of ea ch compone nt, and in teractivel y develop and test c omponents. | |
1714 | ||
1715 | First, ins tall the f ollowing n pm package globally: | |
1716 | ||
1717 | ```sh | |
1718 | npm instal l -g @stor ybook/cli | |
1719 | ``` | |
1720 | ||
1721 | Then, run the follow ing comman d inside y our app’ s director y: | |
1722 | ||
1723 | ```sh | |
1724 | getstorybo ok | |
1725 | ``` | |
1726 | ||
1727 | After that , follow t he instruc tions on t he screen. | |
1728 | ||
1729 | Learn more about Rea ct Storybo ok: | |
1730 | ||
1731 | * Screenca st: [Getti ng Started with Reac t Storyboo k](https:/ /egghead.i o/lessons/ react-gett ing-starte d-with-rea ct-storybo ok) | |
1732 | * [GitHub Repo](http s://github .com/story books/stor ybook) | |
1733 | * [Documen tation](ht tps://stor ybook.js.o rg/basics/ introducti on/) | |
1734 | * [Snapsho t Testing UI](https: //github.c om/storybo oks/storyb ook/tree/m aster/addo ns/storysh ots) with Storybook + addon/st oryshot | |
1735 | ||
1736 | ### Gettin g Started with Style guidist | |
1737 | ||
1738 | Styleguidi st combine s a style guide, whe re all you r componen ts are pre sented on a single p age with t heir props documenta tion and u sage examp les, with an environ ment for d eveloping components in isolat ion, simil ar to Stor ybook. In Styleguidi st you wri te example s in Markd own, where each code snippet i s rendered as a live editable playground . | |
1739 | ||
1740 | First, ins tall Style guidist: | |
1741 | ||
1742 | ```sh | |
1743 | npm instal l --save r eact-style guidist | |
1744 | ``` | |
1745 | ||
1746 | Alternativ ely you ma y use `yar n`: | |
1747 | ||
1748 | ```sh | |
1749 | yarn add r eact-style guidist | |
1750 | ``` | |
1751 | ||
1752 | Then, add these scri pts to you r `package .json`: | |
1753 | ||
1754 | ```diff | |
1755 | "script s": { | |
1756 | + "styl eguide": " styleguidi st server" , | |
1757 | + "styl eguide:bui ld": "styl eguidist b uild", | |
1758 | "star t": "react -scripts s tart", | |
1759 | ``` | |
1760 | ||
1761 | Then, run the follow ing comman d inside y our app’ s director y: | |
1762 | ||
1763 | ```sh | |
1764 | npm run st yleguide | |
1765 | ``` | |
1766 | ||
1767 | After that , follow t he instruc tions on t he screen. | |
1768 | ||
1769 | Learn more about Rea ct Stylegu idist: | |
1770 | ||
1771 | * [GitHub Repo](http s://github .com/style guidist/re act-styleg uidist) | |
1772 | * [Documen tation](ht tps://reac t-stylegui dist.js.or g/docs/get ting-start ed.html) | |
1773 | ||
1774 | ## Publish ing Compon ents to np m | |
1775 | ||
1776 | Create Rea ct App doe sn't provi de any bui lt-in func tionality to publish a compone nt to npm. If you're ready to extract a component from your project so other peo ple can us e it, we r ecommend m oving it t o a separa te directo ry outside of your p roject and then usin g a tool l ike [nwb]( https://gi thub.com/i nsin/nwb#r eact-compo nents-and- libraries) to prepar e it for p ublishing. | |
1777 | ||
1778 | ## Making a Progress ive Web Ap p | |
1779 | ||
1780 | By default , the prod uction bui ld is a fu lly functi onal, offl ine-first | |
1781 | [Progressi ve Web App ](https:// developers .google.co m/web/prog ressive-we b-apps/). | |
1782 | ||
1783 | Progressiv e Web Apps are faste r and more reliable than tradi tional web pages, an d provide an engagin g mobile e xperience: | |
1784 | ||
1785 | * All sta tic site a ssets are cached so that your page loads fast on s ubsequent visits, re gardless o f network connectivi ty (such a s 2G or 3G ). Updates are downl oaded in t he backgro und. | |
1786 | * Your ap p will wor k regardle ss of netw ork state, even if o ffline. Th is means y our users will be ab le to use your app a t 10,000 f eet and on the subwa y. | |
1787 | * On mobi le devices , your app can be ad ded direct ly to the user's hom e screen, app icon a nd all. Yo u can also re-engage users usi ng web **p ush notifi cations**. This elim inates the need for the app st ore. | |
1788 | ||
1789 | The [`sw-p recache-we bpack-plug in`](https ://github. com/goldha nd/sw-prec ache-webpa ck-plugin) | |
1790 | is integra ted into p roduction configurat ion, | |
1791 | and it wil l take car e of gener ating a se rvice work er file th at will au tomaticall y | |
1792 | precache a ll of your local ass ets and ke ep them up to date a s you depl oy updates . | |
1793 | The servic e worker w ill use a [cache-fir st strateg y](https:/ /developer s.google.c om/web/fun damentals/ instant-an d-offline/ offline-co okbook/#ca che-fallin g-back-to- network) | |
1794 | for handli ng all req uests for local asse ts, includ ing the in itial HTML , ensuring | |
1795 | that your web app is reliably fast, even on a slow or unreli able netwo rk. | |
1796 | ||
1797 | ### Opting Out of Ca ching | |
1798 | ||
1799 | If you wou ld prefer not to ena ble servic e workers prior to y our initia l | |
1800 | production deploymen t, then re move the c all to `re gisterServ iceWorker( )` | |
1801 | from [`src /index.js` ](src/inde x.js). | |
1802 | ||
1803 | If you had previousl y enabled service wo rkers in y our produc tion deplo yment and | |
1804 | have decid ed that yo u would li ke to disa ble them f or all you r existing users, | |
1805 | you can sw ap out the call to ` registerSe rviceWorke r()` in | |
1806 | [`src/inde x.js`](src /index.js) first by modifying the servic e worker i mport: | |
1807 | ```javascr ipt | |
1808 | import { u nregister } from './ registerSe rviceWorke r'; | |
1809 | ``` | |
1810 | and then c all `unreg ister()` i nstead. | |
1811 | After the user visit s a page t hat has `u nregister( )`, | |
1812 | the servic e worker w ill be uni nstalled. Note that depending on how `/s ervice-wor ker.js` is served, | |
1813 | it may tak e up to 24 hours for the cache to be inv alidated. | |
1814 | ||
1815 | ### Offlin e-First Co nsideratio ns | |
1816 | ||
1817 | 1. Service workers [ require HT TPS](https ://develop ers.google .com/web/f undamental s/getting- started/pr imers/serv ice-worker s#you_need _https), | |
1818 | although t o facilita te local t esting, th at policy | |
1819 | [does not apply to ` localhost` ](http://s tackoverfl ow.com/que stions/341 60509/opti ons-for-te sting-serv ice-worker s-via-http /34161385# 34161385). | |
1820 | If your pr oduction w eb server does not s upport HTT PS, then t he service worker | |
1821 | registrati on will fa il, but th e rest of your web a pp will re main funct ional. | |
1822 | ||
1823 | 1. Service workers a re [not cu rrently su pported](h ttps://jak earchibald .github.io /isservice workerread y/) | |
1824 | in all web browsers. Service w orker regi stration [ won't be a ttempted]( src/regist erServiceW orker.js) | |
1825 | on browser s that lac k support. | |
1826 | ||
1827 | 1. The ser vice worke r is only enabled in the [prod uction env ironment]( #deploymen t), | |
1828 | e.g. the o utput of ` npm run bu ild`. It's recommend ed that yo u do not e nable an | |
1829 | offline-fi rst servic e worker i n a develo pment envi ronment, a s it can l ead to | |
1830 | frustratio n when pre viously ca ched asset s are used and do no t include the latest | |
1831 | changes yo u've made locally. | |
1832 | ||
1833 | 1. If you *need* to test your offline-fi rst servic e worker l ocally, bu ild | |
1834 | the applic ation (usi ng `npm ru n build`) and run a simple htt p server f rom your | |
1835 | build dire ctory. Aft er running the build script, ` create-rea ct-app` wi ll give | |
1836 | instructio ns for one way to te st your pr oduction b uild local ly and the [deployme nt instruc tions](#de ployment) have | |
1837 | instructio ns for usi ng other m ethods. *B e sure to always use an | |
1838 | incognito window to avoid comp lications with your browser ca che.* | |
1839 | ||
1840 | 1. If poss ible, conf igure your productio n environm ent to ser ve the gen erated | |
1841 | `service-w orker.js` [with HTTP caching d isabled](h ttp://stac koverflow. com/questi ons/388439 70/service -worker-ja vascript-u pdate-freq uency-ever y-24-hours ). | |
1842 | If that's not possib le—[GitH ub Pages]( #github-pa ges), for instance, does not | |
1843 | allow you to change the defaul t 10 minut e HTTP cac he lifetim e—then b e aware | |
1844 | that if yo u visit yo ur product ion site, and then r evisit aga in before | |
1845 | `service-w orker.js` has expire d from you r HTTP cac he, you'll continue to get | |
1846 | the previo usly cache d assets f rom the se rvice work er. If you have an i mmediate | |
1847 | need to vi ew your up dated prod uction dep loyment, p erforming a shift-re fresh | |
1848 | will tempo rarily dis able the s ervice wor ker and re trieve all assets fr om the | |
1849 | network. | |
1850 | ||
1851 | 1. Users a ren't alwa ys familia r with off line-first web apps. It can be useful to | |
1852 | [let the u ser know]( https://de velopers.g oogle.com/ web/fundam entals/ins tant-and-o ffline/off line-ux#in form_the_u ser_when_t he_app_is_ ready_for_ offline_co nsumption) | |
1853 | when the s ervice wor ker has fi nished pop ulating yo ur caches (showing a "This web | |
1854 | app works offline!" message) a nd also le t them kno w when the service w orker has | |
1855 | fetched th e latest u pdates tha t will be available the next t ime they l oad the | |
1856 | page (show ing a "New content i s availabl e; please refresh." message). Showing | |
1857 | this messa ges is cur rently lef t as an ex ercise to the develo per, but a s a | |
1858 | starting p oint, you can make u se of the logic incl uded in [` src/regist erServiceW orker.js`] (src/regis terService Worker.js) , which | |
1859 | demonstrat es which s ervice wor ker lifecy cle events to listen for to de tect each | |
1860 | scenario, and which as a defau lt, just l ogs approp riate mess ages to th e | |
1861 | JavaScript console. | |
1862 | ||
1863 | 1. By defa ult, the g enerated s ervice wor ker file w ill not in tercept or cache any | |
1864 | cross-orig in traffic , like HTT P [API req uests](#in tegrating- with-an-ap i-backend) , | |
1865 | images, or embeds lo aded from a differen t domain. If you wou ld like to use a | |
1866 | runtime ca ching stra tegy for t hose reque sts, you c an [`eject `](#npm-ru n-eject) | |
1867 | and then c onfigure t he | |
1868 | [`runtimeC aching`](h ttps://git hub.com/Go ogleChrome /sw-precac he#runtime caching-ar rayobject) | |
1869 | option in the `SWPre cacheWebpa ckPlugin` section of | |
1870 | [`webpack. config.pro d.js`](../ config/web pack.confi g.prod.js) . | |
1871 | ||
1872 | ### Progre ssive Web App Metada ta | |
1873 | ||
1874 | The defaul t configur ation incl udes a web app manif est locate d at | |
1875 | [`public/m anifest.js on`](publi c/manifest .json), th at you can customize with | |
1876 | details sp ecific to your web a pplication . | |
1877 | ||
1878 | When a use r adds a w eb app to their home screen usi ng Chrome or Firefox on | |
1879 | Android, t he metadat a in [`man ifest.json `](public/ manifest.j son) deter mines what | |
1880 | icons, nam es, and br anding col ors to use when the web app is displayed . | |
1881 | [The Web A pp Manifes t guide](h ttps://dev elopers.go ogle.com/w eb/fundame ntals/enga ge-and-ret ain/web-ap p-manifest /) | |
1882 | provides m ore contex t about wh at each fi eld means, and how y our custom izations | |
1883 | will affec t your use rs' experi ence. | |
1884 | ||
1885 | ## Analyzi ng the Bun dle Size | |
1886 | ||
1887 | [Source ma p explorer ](https:// www.npmjs. com/packag e/source-m ap-explore r) analyze s | |
1888 | JavaScript bundles u sing the s ource maps . This hel ps you und erstand wh ere code | |
1889 | bloat is c oming from . | |
1890 | ||
1891 | To add Sou rce map ex plorer to a Create R eact App p roject, fo llow these steps: | |
1892 | ||
1893 | ```sh | |
1894 | npm instal l --save s ource-map- explorer | |
1895 | ``` | |
1896 | ||
1897 | Alternativ ely you ma y use `yar n`: | |
1898 | ||
1899 | ```sh | |
1900 | yarn add s ource-map- explorer | |
1901 | ``` | |
1902 | ||
1903 | Then in `p ackage.jso n`, add th e followin g line to `scripts`: | |
1904 | ||
1905 | ```diff | |
1906 | "script s": { | |
1907 | + "anal yze": "sou rce-map-ex plorer bui ld/static/ js/main.*" , | |
1908 | "star t": "react -scripts s tart", | |
1909 | "buil d": "react -scripts b uild", | |
1910 | "test ": "react- scripts te st --env=j sdom", | |
1911 | ``` | |
1912 | ||
1913 | Then to an alyze the bundle run the produ ction buil d then run the analy ze | |
1914 | script. | |
1915 | ||
1916 | ``` | |
1917 | npm run bu ild | |
1918 | npm run an alyze | |
1919 | ``` | |
1920 | ||
1921 | ## Deploym ent | |
1922 | ||
1923 | `npm run b uild` crea tes a `bui ld` direct ory with a productio n build of your app. Set up yo ur favorit e HTTP ser ver so tha t a visito r to your site is se rved `inde x.html`, a nd request s to stati c paths li ke `/stati c/js/main. <hash>.js` are serve d with the contents of the `/s tatic/js/m ain.<hash> .js` file. | |
1924 | ||
1925 | ### Static Server | |
1926 | ||
1927 | For enviro nments usi ng [Node]( https://no dejs.org/) , the easi est way to handle th is would b e to insta ll [serve] (https://g ithub.com/ zeit/serve ) and let it handle the rest: | |
1928 | ||
1929 | ```sh | |
1930 | npm instal l -g serve | |
1931 | serve -s b uild | |
1932 | ``` | |
1933 | ||
1934 | The last c ommand sho wn above w ill serve your stati c site on the port * *5000**. L ike many o f [serve]( https://gi thub.com/z eit/serve) ’s inter nal settin gs, the po rt can be adjusted u sing the ` -p` or `-- port` flag s. | |
1935 | ||
1936 | Run this c ommand to get a full list of t he options available : | |
1937 | ||
1938 | ```sh | |
1939 | serve -h | |
1940 | ``` | |
1941 | ||
1942 | ### Other Solutions | |
1943 | ||
1944 | You don’ t necessar ily need a static se rver in or der to run a Create React App project in productio n. It work s just as fine integ rated into an existi ng dynamic one. | |
1945 | ||
1946 | Here’s a programma tic exampl e using [N ode](https ://nodejs. org/) and [Express]( http://exp ressjs.com /): | |
1947 | ||
1948 | ```javascr ipt | |
1949 | const expr ess = requ ire('expre ss'); | |
1950 | const path = require ('path'); | |
1951 | const app = express( ); | |
1952 | ||
1953 | app.use(ex press.stat ic(path.jo in(__dirna me, 'build '))); | |
1954 | ||
1955 | app.get('/ ', functio n (req, re s) { | |
1956 | res.send File(path. join(__dir name, 'bui ld', 'inde x.html')); | |
1957 | }); | |
1958 | ||
1959 | app.listen (9000); | |
1960 | ``` | |
1961 | ||
1962 | The choice of your s erver soft ware isn†™t importa nt either. Since Cre ate React App is com pletely pl atform-agn ostic, the re’s no need to ex plicitly u se Node. | |
1963 | ||
1964 | The `build ` folder w ith static assets is the only output pro duced by C reate Reac t App. | |
1965 | ||
1966 | However th is is not quite enou gh if you use client -side rout ing. Read the next s ection if you want t o support URLs like `/todos/42 ` in your single-pag e app. | |
1967 | ||
1968 | ### Servin g Apps wit h Client-S ide Routin g | |
1969 | ||
1970 | If you use routers t hat use th e HTML5 [` pushState` history A PI](https: //develope r.mozilla. org/en-US/ docs/Web/A PI/History _API#Addin g_and_modi fying_hist ory_entrie s) under t he hood (f or example , [React R outer](htt ps://githu b.com/Reac tTraining/ react-rout er) with ` browserHis tory`), ma ny static file serve rs will fa il. For ex ample, if you used R eact Route r with a r oute for ` /todos/42` , the deve lopment se rver will respond to `localhos t:3000/tod os/42` pro perly, but an Expres s serving a producti on build a s above wi ll not. | |
1971 | ||
1972 | This is be cause when there is a fresh pa ge load fo r a `/todo s/42`, the server lo oks for th e file `bu ild/todos/ 42` and do es not fin d it. The server nee ds to be c onfigured to respond to a requ est to `/t odos/42` b y serving `index.htm l`. For ex ample, we can amend our Expres s example above to s erve `inde x.html` fo r any unkn own paths: | |
1973 | ||
1974 | ```diff | |
1975 | app.use(e xpress.sta tic(path.j oin(__dirn ame, 'buil d'))); | |
1976 | ||
1977 | -app.get(' /', functi on (req, r es) { | |
1978 | +app.get(' /*', funct ion (req, res) { | |
1979 | res.sen dFile(path .join(__di rname, 'bu ild', 'ind ex.html')) ; | |
1980 | }); | |
1981 | ``` | |
1982 | ||
1983 | If you’r e using [A pache HTTP Server](h ttps://htt pd.apache. org/), you need to c reate a `. htaccess` file in th e `public` folder th at looks l ike this: | |
1984 | ||
1985 | ``` | |
1986 | Option s -MultiVi ews | |
1987 | Rewrit eEngine On | |
1988 | Rewrit eCond %{RE QUEST_FILE NAME} !-f | |
1989 | Rewrit eRule ^ in dex.html [ QSA,L] | |
1990 | ``` | |
1991 | ||
1992 | It will ge t copied t o the `bui ld` folder when you run `npm r un build`. | |
1993 | ||
1994 | If you’r e using [A pache Tomc at](http:/ /tomcat.ap ache.org/) , you need to follow [this Sta ck Overflo w answer]( https://st ackoverflo w.com/a/41 249464/487 8474). | |
1995 | ||
1996 | Now reques ts to `/to dos/42` wi ll be hand led correc tly both i n developm ent and in productio n. | |
1997 | ||
1998 | On a produ ction buil d, and in a browser that suppo rts [servi ce workers ](https:// developers .google.co m/web/fund amentals/g etting-sta rted/prime rs/service -workers), | |
1999 | the servic e worker w ill automa tically ha ndle all n avigation requests, like for | |
2000 | `/todos/42 `, by serv ing the ca ched copy of your `i ndex.html` . This | |
2001 | service wo rker navig ation rout ing can be configure d or disab led by | |
2002 | [`eject`in g](#npm-ru n-eject) a nd then mo difying th e | |
2003 | [`navigate Fallback`] (https://g ithub.com/ GoogleChro me/sw-prec ache#navig atefallbac k-string) | |
2004 | and [`navi gateFallba ckWhitelis t`](https: //github.c om/GoogleC hrome/sw-p recache#na vigatefall backwhitel ist-arrayr egexp) | |
2005 | options of the `SWPr eachePlugi n` [config uration](. ./config/w ebpack.con fig.prod.j s). | |
2006 | ||
2007 | When users install y our app to the homes creen of t heir devic e the defa ult config uration wi ll make a shortcut t o `/index. html`. Thi s may not work for c lient-side routers w hich expec t the app to be serv ed from `/ `. Edit th e web app manifest a t [`public /manifest. json`](pub lic/manife st.json) a nd change `start_url ` to match the requi red URL sc heme, for example: | |
2008 | ||
2009 | ```js | |
2010 | "start_u rl": ".", | |
2011 | ``` | |
2012 | ||
2013 | ### Buildi ng for Rel ative Path s | |
2014 | ||
2015 | By default , Create R eact App p roduces a build assu ming your app is hos ted at the server ro ot.<br> | |
2016 | To overrid e this, sp ecify the `homepage` in your ` package.js on`, for e xample: | |
2017 | ||
2018 | ```js | |
2019 | "homepag e": "http: //mywebsit e.com/rela tivepath", | |
2020 | ``` | |
2021 | ||
2022 | This will let Create React App correctly infer the root path to use in the gener ated HTML file. | |
2023 | ||
2024 | **Note**: If you are using `re act-router @^4`, you can root ` <Link>`s u sing the ` basename` prop on an y `<Router >`.<br> | |
2025 | More infor mation [he re](https: //reacttra ining.com/ react-rout er/web/api /BrowserRo uter/basen ame-string ).<br> | |
2026 | <br> | |
2027 | For exampl e: | |
2028 | ```js | |
2029 | <BrowserRo uter basen ame="/cale ndar"/> | |
2030 | <Link to=" /today"/> // renders <a href=" /calendar/ today"> | |
2031 | ``` | |
2032 | ||
2033 | #### Servi ng the Sam e Build fr om Differe nt Paths | |
2034 | ||
2035 | >Note: thi s feature is availab le with `r eact-scrip ts@0.9.0` and higher . | |
2036 | ||
2037 | If you are not using the HTML5 `pushStat e` history API or no t using cl ient-side routing at all, it i s unnecess ary to spe cify the U RL from wh ich your a pp will be served. I nstead, yo u can put this in yo ur `packag e.json`: | |
2038 | ||
2039 | ```js | |
2040 | "homepag e": ".", | |
2041 | ``` | |
2042 | ||
2043 | This will make sure that all t he asset p aths are r elative to `index.ht ml`. You w ill then b e able to move your app from ` http://myw ebsite.com ` to `http ://mywebsi te.com/rel ativepath` or even ` http://myw ebsite.com /relative/ path` with out having to rebuil d it. | |
2044 | ||
2045 | ### [Azure ](https:// azure.micr osoft.com/ ) | |
2046 | ||
2047 | See [this] (https://m edium.com/ @to_pe/dep loying-cre ate-react- app-on-mic rosoft-azu re-c0f6686 a4321) blo g post on how to dep loy your R eact app t o Microsof t Azure. | |
2048 | ||
2049 | See [this] (https://m edium.com/ @strid/hos t-create-r eact-app-o n-azure-98 6bc40d5bf2 #.pycfnafb g) blog po st or [thi s](https:/ /github.co m/ulrikaug ustsson/az ure-appser vice-stati c) repo fo r a way to use autom atic deplo yment to A zure App S ervice. | |
2050 | ||
2051 | ### [Fireb ase](https ://firebas e.google.c om/) | |
2052 | ||
2053 | Install th e Firebase CLI if yo u haven’ t already by running `npm inst all -g fir ebase-tool s`. Sign u p for a [F irebase ac count](htt ps://conso le.firebas e.google.c om/) and c reate a ne w project. Run `fire base login ` and logi n with you r previous created F irebase ac count. | |
2054 | ||
2055 | Then run t he `fireba se init` c ommand fro m your pro ject’s r oot. You n eed to cho ose the ** Hosting: C onfigure a nd deploy Firebase H osting sit es** and c hoose the Firebase p roject you created i n the prev ious step. You will need to ag ree with ` database.r ules.json` being cre ated, choo se `build` as the pu blic direc tory, and also agree to **Conf igure as a single-pa ge app** b y replying with `y`. | |
2056 | ||
2057 | ```sh | |
2058 | === Pr oject Setu p | |
2059 | ||
2060 | First, let's ass ociate thi s project directory with a Fir ebase proj ect. | |
2061 | You ca n create m ultiple pr oject alia ses by run ning fireb ase use -- add, | |
2062 | but fo r now we'l l just set up a defa ult projec t. | |
2063 | ||
2064 | ? What Firebase project do you want to associa te as defa ult? Examp le app (ex ample-app- fd690) | |
2065 | ||
2066 | === Da tabase Set up | |
2067 | ||
2068 | Fireba se Realtim e Database Rules all ow you to define how your data should be | |
2069 | struct ured and w hen your d ata can be read from and writt en to. | |
2070 | ||
2071 | ? What file shou ld be used for Datab ase Rules? database. rules.json | |
2072 | ✔ D atabase Ru les for ex ample-app- fd690 have been down loaded to database.r ules.json. | |
2073 | Future modificat ions to da tabase.rul es.json wi ll update Database R ules when you run | |
2074 | fireba se deploy. | |
2075 | ||
2076 | === Ho sting Setu p | |
2077 | ||
2078 | Your p ublic dire ctory is t he folder (relative to your pr oject dire ctory) tha t | |
2079 | will c ontain Hos ting asset s to uploa ded with f irebase de ploy. If y ou | |
2080 | have a build pro cess for y our assets , use your build's o utput dire ctory. | |
2081 | ||
2082 | ? What do you wa nt to use as your pu blic direc tory? buil d | |
2083 | ? Conf igure as a single-pa ge app (re write all urls to /i ndex.html) ? Yes | |
2084 | ✔ W rote build /index.htm l | |
2085 | ||
2086 | i Wri ting confi guration i nfo to fir ebase.json ... | |
2087 | i Wri ting proje ct informa tion to .f irebaserc. .. | |
2088 | ||
2089 | ✔ F irebase in itializati on complet e! | |
2090 | ``` | |
2091 | ||
2092 | IMPORTANT: you need to set pro per HTTP c aching hea ders for ` service-wo rker.js` f ile in `fi rebase.jso n` file or you will not be abl e to see c hanges aft er first d eployment ([issue #2 440](https ://github. com/facebo okincubato r/create-r eact-app/i ssues/2440 )). It sho uld be add ed inside `"hosting" ` key like next: | |
2093 | ||
2094 | ``` | |
2095 | { | |
2096 | "hosting ": { | |
2097 | ... | |
2098 | "heade rs": [ | |
2099 | {"so urce": "/s ervice-wor ker.js", " headers": [{"key": " Cache-Cont rol", "val ue": "no-c ache"}]} | |
2100 | ] | |
2101 | ... | |
2102 | ``` | |
2103 | ||
2104 | Now, after you creat e a produc tion build with `npm run build `, you can deploy it by runnin g `firebas e deploy`. | |
2105 | ||
2106 | ```sh | |
2107 | === De ploying to 'example- app-fd690' ... | |
2108 | ||
2109 | i dep loying dat abase, hos ting | |
2110 | ✔ d atabase: r ules ready to deploy . | |
2111 | i hos ting: prep aring buil d director y for uplo ad... | |
2112 | Upload ing: [==== ========== ========== ====== ] 75 %✔ host ing: build folder up loaded suc cessfully | |
2113 | ✔ h osting: 8 files uplo aded succe ssfully | |
2114 | i sta rting rele ase proces s (may tak e several minutes).. . | |
2115 | ||
2116 | ✔ D eploy comp lete! | |
2117 | ||
2118 | Projec t Console: https://c onsole.fir ebase.goog le.com/pro ject/examp le-app-fd6 90/overvie w | |
2119 | Hostin g URL: htt ps://examp le-app-fd6 90.firebas eapp.com | |
2120 | ``` | |
2121 | ||
2122 | For more i nformation see [Add Firebase t o your Jav aScript Pr oject](htt ps://fireb ase.google .com/docs/ web/setup) . | |
2123 | ||
2124 | ### [GitHu b Pages](h ttps://pag es.github. com/) | |
2125 | ||
2126 | >Note: thi s feature is availab le with `r eact-scrip ts@0.2.0` and higher . | |
2127 | ||
2128 | #### Step 1: Add `ho mepage` to `package. json` | |
2129 | ||
2130 | **The step below is important! **<br> | |
2131 | **If you s kip it, yo ur app wil l not depl oy correct ly.** | |
2132 | ||
2133 | Open your `package.j son` and a dd a `home page` fiel d for your project: | |
2134 | ||
2135 | ```json | |
2136 | "homepag e": "https ://myusern ame.github .io/my-app ", | |
2137 | ``` | |
2138 | ||
2139 | or for a G itHub user page: | |
2140 | ||
2141 | ```json | |
2142 | "homepag e": "https ://myusern ame.github .io", | |
2143 | ``` | |
2144 | ||
2145 | Create Rea ct App use s the `hom epage` fie ld to dete rmine the root URL i n the buil t HTML fil e. | |
2146 | ||
2147 | #### Step 2: Install `gh-pages ` and add `deploy` t o `scripts ` in `pack age.json` | |
2148 | ||
2149 | Now, whene ver you ru n `npm run build`, y ou will se e a cheat sheet with instructi ons on how to deploy to GitHub Pages. | |
2150 | ||
2151 | To publish it at [ht tps://myus ername.git hub.io/my- app](https ://myusern ame.github .io/my-app ), run: | |
2152 | ||
2153 | ```sh | |
2154 | npm instal l --save g h-pages | |
2155 | ``` | |
2156 | ||
2157 | Alternativ ely you ma y use `yar n`: | |
2158 | ||
2159 | ```sh | |
2160 | yarn add g h-pages | |
2161 | ``` | |
2162 | ||
2163 | Add the fo llowing sc ripts in y our `packa ge.json`: | |
2164 | ||
2165 | ```diff | |
2166 | "scripts ": { | |
2167 | + "prede ploy": "np m run buil d", | |
2168 | + "deplo y": "gh-pa ges -d bui ld", | |
2169 | "start ": "react- scripts st art", | |
2170 | "build ": "react- scripts bu ild", | |
2171 | ``` | |
2172 | ||
2173 | The `prede ploy` scri pt will ru n automati cally befo re `deploy ` is run. | |
2174 | ||
2175 | If you are deploying to a GitH ub user pa ge instead of a proj ect page y ou'll need to make t wo | |
2176 | additional modificat ions: | |
2177 | ||
2178 | 1. First, change you r reposito ry's sourc e branch t o be any b ranch othe r than **m aster**. | |
2179 | 1. Additio nally, twe ak your `p ackage.jso n` scripts to push d eployments to **mast er**: | |
2180 | ```diff | |
2181 | "scripts ": { | |
2182 | "prede ploy": "np m run buil d", | |
2183 | - "deplo y": "gh-pa ges -d bui ld", | |
2184 | + "deplo y": "gh-pa ges -b mas ter -d bui ld", | |
2185 | ``` | |
2186 | ||
2187 | #### Step 3: Deploy the site b y running `npm run d eploy` | |
2188 | ||
2189 | Then run: | |
2190 | ||
2191 | ```sh | |
2192 | npm run de ploy | |
2193 | ``` | |
2194 | ||
2195 | #### Step 4: Ensure your proje ct’s set tings use `gh-pages` | |
2196 | ||
2197 | Finally, m ake sure * *GitHub Pa ges** opti on in your GitHub pr oject sett ings is se t to use t he `gh-pag es` branch : | |
2198 | ||
2199 | <img src=" http://i.i mgur.com/H UjEr9l.png " width="5 00" alt="g h-pages br anch setti ng"> | |
2200 | ||
2201 | #### Step 5: Optiona lly, confi gure the d omain | |
2202 | ||
2203 | You can co nfigure a custom dom ain with G itHub Page s by addin g a `CNAME ` file to the `publi c/` folder . | |
2204 | ||
2205 | #### Notes on client -side rout ing | |
2206 | ||
2207 | GitHub Pag es doesn†™t support routers t hat use th e HTML5 `p ushState` history AP I under th e hood (fo r example, React Rou ter using `browserHi story`). T his is bec ause when there is a fresh pag e load for a url lik e `http:// user.githu b.io/todom vc/todos/4 2`, where `/todos/42 ` is a fro ntend rout e, the Git Hub Pages server ret urns 404 b ecause it knows noth ing of `/t odos/42`. If you wan t to add a router to a project hosted on GitHub Pa ges, here are a coup le of solu tions: | |
2208 | ||
2209 | * You coul d switch f rom using HTML5 hist ory API to routing w ith hashes . If you u se React R outer, you can switc h to `hash History` f or this ef fect, but the URL wi ll be long er and mor e verbose (for examp le, `http: //user.git hub.io/tod omvc/#/tod os/42?_k=y knaj`). [R ead more]( https://re acttrainin g.com/reac t-router/w eb/api/Rou ter) about different history i mplementat ions in Re act Router . | |
2210 | * Alternat ively, you can use a trick to teach GitH ub Pages t o handle 4 04 by redi recting to your `ind ex.html` p age with a special r edirect pa rameter. Y ou would n eed to add a `404.ht ml` file w ith the re direction code to th e `build` folder bef ore deploy ing your p roject, an d you’ll need to a dd code ha ndling the redirect parameter to `index. html`. You can find a detailed explanati on of this technique [in this guide](htt ps://githu b.com/rafr ex/spa-git hub-pages) . | |
2211 | ||
2212 | #### Troub leshooting | |
2213 | ||
2214 | ##### "/de v/tty: No such a dev ice or add ress" | |
2215 | ||
2216 | If, when d eploying, you get `/ dev/tty: N o such a d evice or a ddress` or a similar error, tr y the foll wing: | |
2217 | ||
2218 | 1. Create a new [Per sonal Acce ss Token]( https://gi thub.com/s ettings/to kens) | |
2219 | 2. `git re mote set-u rl origin https://<u ser>:<toke n>@github. com/<user> /<repo>` . | |
2220 | 3. Try `np m run depl oy again` | |
2221 | ||
2222 | ### [Herok u](https:/ /www.herok u.com/) | |
2223 | ||
2224 | Use the [H eroku Buil dpack for Create Rea ct App](ht tps://gith ub.com/mar s/create-r eact-app-b uildpack). <br> | |
2225 | You can fi nd instruc tions in [ Deploying React with Zero Conf iguration] (https://b log.heroku .com/deplo ying-react -with-zero -configura tion). | |
2226 | ||
2227 | #### Resol ving Herok u Deployme nt Errors | |
2228 | ||
2229 | Sometimes `npm run b uild` work s locally but fails during dep loy via He roku. Foll owing are the most c ommon case s. | |
2230 | ||
2231 | ##### "Mod ule not fo und: Error : Cannot r esolve 'fi le' or 'di rectory'" | |
2232 | ||
2233 | If you get something like this : | |
2234 | ||
2235 | ``` | |
2236 | remote: Fa iled to cr eate a pro duction bu ild. Reaso n: | |
2237 | remote: Mo dule not f ound: Erro r: Cannot resolve 'f ile' or 'd irectory' | |
2238 | MyDirector y in /tmp/ build_1234 /src | |
2239 | ``` | |
2240 | ||
2241 | It means y ou need to ensure th at the let tercase of the file or directo ry you `im port` matc hes the on e you see on your fi lesystem o r on GitHu b. | |
2242 | ||
2243 | This is im portant be cause Linu x (the ope rating sys tem used b y Heroku) is case se nsitive. S o `MyDirec tory` and `mydirecto ry` are tw o distinct directori es and thu s, even th ough the p roject bui lds locall y, the dif ference in case brea ks the `im port` stat ements on Heroku rem otes. | |
2244 | ||
2245 | ##### "Cou ld not fin d a requir ed file." | |
2246 | ||
2247 | If you exc lude or ig nore neces sary files from the package yo u will see a error s imilar thi s one: | |
2248 | ||
2249 | ``` | |
2250 | remote: Co uld not fi nd a requi red file. | |
2251 | remote: Name: `ind ex.html` | |
2252 | remote: Searched i n: /tmp/bu ild_a2875f c163b20922 5122d68916 f1d4df/pub lic | |
2253 | remote: | |
2254 | remote: np m ERR! Lin ux 3.13.0- 105-generi c | |
2255 | remote: np m ERR! arg v "/tmp/bu ild_a2875f c163b20922 5122d68916 f1d4df/.he roku/node/ bin/node" "/tmp/buil d_a2875fc1 63b2092251 22d68916f1 d4df/.hero ku/node/bi n/npm" "ru n" "build" | |
2256 | ``` | |
2257 | ||
2258 | In this ca se, ensure that the file is th ere with t he proper lettercase and thatâ €™s not ig nored on y our local `.gitignor e` or `~/. gitignore_ global`. | |
2259 | ||
2260 | ### [Netli fy](https: //www.netl ify.com/) | |
2261 | ||
2262 | **To do a manual dep loy to Net lify’s C DN:** | |
2263 | ||
2264 | ```sh | |
2265 | npm instal l netlify- cli -g | |
2266 | netlify de ploy | |
2267 | ``` | |
2268 | ||
2269 | Choose `bu ild` as th e path to deploy. | |
2270 | ||
2271 | **To setup continuou s delivery :** | |
2272 | ||
2273 | With this setup Netl ify will b uild and d eploy when you push to git or open a pul l request: | |
2274 | ||
2275 | 1. [Start a new netl ify projec t](https:/ /app.netli fy.com/sig nup) | |
2276 | 2. Pick yo ur Git hos ting servi ce and sel ect your r epository | |
2277 | 3. Set `ya rn build` as the bui ld command and `buil d` as the publish di rectory | |
2278 | 4. Click ` Deploy sit e` | |
2279 | ||
2280 | **Support for client -side rout ing:** | |
2281 | ||
2282 | To support `pushStat e`, make s ure to cre ate a `pub lic/_redir ects` file with the following rewrite ru les: | |
2283 | ||
2284 | ``` | |
2285 | /* /index .html 200 | |
2286 | ``` | |
2287 | ||
2288 | When you b uild the p roject, Cr eate React App will place the `public` f older cont ents into the build output. | |
2289 | ||
2290 | ### [Now]( https://ze it.co/now) | |
2291 | ||
2292 | Now offers a zero-co nfiguratio n single-c ommand dep loyment. Y ou can use `now` to deploy you r app for free. | |
2293 | ||
2294 | 1. Install the `now` command-l ine tool e ither via the recomm ended [des ktop tool] (https://z eit.co/dow nload) or via node w ith `npm i nstall -g now`. | |
2295 | ||
2296 | 2. Build y our app by running ` npm run bu ild`. | |
2297 | ||
2298 | 3. Move in to the bui ld directo ry by runn ing `cd bu ild`. | |
2299 | ||
2300 | 4. Run `no w --name y our-projec t-name` fr om within the build directory. You will see a **no w.sh** URL in your o utput like this: | |
2301 | ||
2302 | ``` | |
2303 | > Read y! https:/ /your-proj ect-name-t pspyhtdtk. now.sh (co pied to cl ipboard) | |
2304 | ``` | |
2305 | ||
2306 | Paste that URL i nto your b rowser whe n the buil d is compl ete, and y ou will se e your dep loyed app. | |
2307 | ||
2308 | Details ar e availabl e in [this article.] (https://z eit.co/blo g/unlimite d-static) | |
2309 | ||
2310 | ### [S3](h ttps://aws .amazon.co m/s3) and [CloudFron t](https:/ /aws.amazo n.com/clou dfront/) | |
2311 | ||
2312 | See this [ blog post] (https://m edium.com/ @omgwtfmar c/deployin g-create-r eact-app-t o-s3-or-cl oudfront-4 8dae4ce0af ) on how t o deploy y our React app to Ama zon Web Se rvices S3 and CloudF ront. | |
2313 | ||
2314 | ### [Surge ](https:// surge.sh/) | |
2315 | ||
2316 | Install th e Surge CL I if you h aven’t a lready by running `n pm install -g surge` . Run the `surge` co mmand and log in you or create a new acc ount. | |
2317 | ||
2318 | When asked about the project p ath, make sure to sp ecify the `build` fo lder, for example: | |
2319 | ||
2320 | ```sh | |
2321 | pro ject path: /path/to/ project/bu ild | |
2322 | ``` | |
2323 | ||
2324 | Note that in order t o support routers th at use HTM L5 `pushSt ate` API, you may wa nt to rena me the `in dex.html` in your bu ild folder to `200.h tml` befor e deployin g to Surge . This [en sures that every URL falls bac k to that file](http s://surge. sh/help/ad ding-a-200 -page-for- client-sid e-routing) . | |
2325 | ||
2326 | ## Advance d Configur ation | |
2327 | ||
2328 | You can ad just vario us develop ment and p roduction settings b y setting environmen t variable s in your shell or w ith [.env] (#adding-d evelopment -environme nt-variabl es-in-env) . | |
2329 | ||
2330 | Variable | Developme nt | Produ ction | Us age | |
2331 | :--- | :-- -: | :---: | :--- | |
2332 | BROWSER | :white_che ck_mark: | :x: | By default, C reate Reac t App will open the default sy stem brows er, favori ng Chrome on macOS. Specify a [browser]( https://gi thub.com/s indresorhu s/opn#app) to overri de this be havior, or set it to `none` to disable i t complete ly. If you need to c ustomize t he way the browser i s launched , you can specify a node scrip t instead. Any argum ents passe d to `npm start` wil l also be passed to this scrip t, and the url where your app is served will be th e last arg ument. You r script's file name must have the `.js` extension . | |
2333 | HOST | :wh ite_check_ mark: | :x : | By def ault, the developmen t web serv er binds t o `localho st`. You m ay use thi s variable to specif y a differ ent host. | |
2334 | PORT | :wh ite_check_ mark: | :x : | By def ault, the developmen t web serv er will at tempt to l isten on p ort 3000 o r prompt y ou to atte mpt the ne xt availab le port. Y ou may use this vari able to sp ecify a di fferent po rt. | |
2335 | HTTPS | :w hite_check _mark: | : x: | When set to `tr ue`, Creat e React Ap p will run the devel opment ser ver in `ht tps` mode. | |
2336 | PUBLIC_URL | :x: | : white_chec k_mark: | Create Rea ct App ass umes your applicatio n is hoste d at the s erving web server's root or a subpath as specified in [`pack age.json` (`homepage `)](#build ing-for-re lative-pat hs). Norma lly, Creat e React Ap p ignores the hostna me. You ma y use this variable to force a ssets to b e referenc ed verbati m to the u rl you pro vide (host name inclu ded). This may be pa rticularly useful wh en using a CDN to ho st your ap plication. | |
2337 | CI | :larg e_orange_d iamond: | :white_che ck_mark: | When set to `true`, Create Re act App tr eats warni ngs as fai lures in t he build. It also ma kes the te st runner non-watchi ng. Most C Is set thi s flag by default. | |
2338 | REACT_EDIT OR | :whit e_check_ma rk: | :x: | When an app crashe s in devel opment, yo u will see an error overlay wi th clickab le stack t race. When you click on it, Cr eate React App will try to det ermine the editor yo u are usin g based on currently running p rocesses, and open t he relevan t source f ile. You c an [send a pull requ est to det ect your e ditor of c hoice](htt ps://githu b.com/face bookincuba tor/create -react-app /issues/26 36). Setti ng this en vironment variable o verrides t he automat ic detecti on. If you do it, ma ke sure yo ur systems [PATH](ht tps://en.w ikipedia.o rg/wiki/PA TH_(variab le)) envir onment var iable poin ts to your editor’ s bin fold er. You ca n also set it to `no ne` to dis able it co mpletely. | |
2339 | CHOKIDAR_U SEPOLLING | :white_c heck_mark: | :x: | W hen set to `true`, t he watcher runs in p olling mod e, as nece ssary insi de a VM. U se this op tion if `n pm start` isn't dete cting chan ges. | |
2340 | GENERATE_S OURCEMAP | :x: | :wh ite_check_ mark: | Wh en set to `false`, s ource maps are not g enerated f or a produ ction buil d. This so lves OOM i ssues on s ome smalle r machines . | |
2341 | NODE_PATH | :white_c heck_mark: | :white _check_mar k: | Same as [`NODE_ PATH` in N ode.js](ht tps://node js.org/api /modules.h tml#module s_loading_ from_the_g lobal_fold ers), but only relat ive folder s are allo wed. Can b e handy fo r emulatin g a monore po setup b y setting `NODE_PATH =src`. | |
2342 | ||
2343 | ## Trouble shooting | |
2344 | ||
2345 | ### `npm s tart` does n’t dete ct changes | |
2346 | ||
2347 | When you s ave a file while `np m start` i s running, the brows er should refresh wi th the upd ated code. <br> | |
2348 | If this do esn’t ha ppen, try one of the following workaroun ds: | |
2349 | ||
2350 | * If your project is in a Drop box folder , try movi ng it out. | |
2351 | * If the w atcher doe sn’t see a file ca lled `inde x.js` and you’re r eferencing it by the folder na me, you [n eed to res tart the w atcher](ht tps://gith ub.com/fac ebookincub ator/creat e-react-ap p/issues/1 164) due t o a Webpac k bug. | |
2352 | * Some edi tors like Vim and In telliJ hav e a “saf e write†feature t hat curren tly breaks the watch er. You wi ll need to disable i t. Follow the instru ctions in [“Adjust ing Your T ext Editor â€](https ://webpack .js.org/gu ides/devel opment/#ad justing-yo ur-text-ed itor). | |
2353 | * If your project pa th contain s parenthe ses, try m oving the project to a path wi thout them . This is caused by a [Webpack watcher b ug](https: //github.c om/webpack /watchpack /issues/42 ). | |
2354 | * On Linux and macOS , you migh t need to [tweak sys tem settin gs](https: //github.c om/webpack /docs/wiki /troublesh ooting#not -enough-wa tchers) to allow mor e watchers . | |
2355 | * If the p roject run s inside a virtual m achine suc h as (a Va grant prov isioned) V irtualBox, create an `.env` fi le in your project d irectory i f it doesn ’t exist , and add `CHOKIDAR_ USEPOLLING =true` to it. This e nsures tha t the next time you run `npm s tart`, the watcher u ses the po lling mode , as neces sary insid e a VM. | |
2356 | ||
2357 | If none of these sol utions hel p please l eave a com ment [in t his thread ](https:// github.com /facebooki ncubator/c reate-reac t-app/issu es/659). | |
2358 | ||
2359 | ### `npm t est` hangs on macOS Sierra | |
2360 | ||
2361 | If you run `npm test ` and the console ge ts stuck a fter print ing `react -scripts t est --env= jsdom` to the consol e there mi ght be a p roblem wit h your [Wa tchman](ht tps://face book.githu b.io/watch man/) inst allation a s describe d in [face bookincuba tor/create -react-app #713](http s://github .com/faceb ookincubat or/create- react-app/ issues/713 ). | |
2362 | ||
2363 | We recomme nd deletin g `node_mo dules` in your proje ct and run ning `npm install` ( or `yarn` if you use it) first . If it do esn't help , you can try one of the numer ous workar ounds ment ioned in t hese issue s: | |
2364 | ||
2365 | * [faceboo k/jest#176 7](https:/ /github.co m/facebook /jest/issu es/1767) | |
2366 | * [faceboo k/watchman #358](http s://github .com/faceb ook/watchm an/issues/ 358) | |
2367 | * [ember-c li/ember-c li#6259](h ttps://git hub.com/em ber-cli/em ber-cli/is sues/6259) | |
2368 | ||
2369 | It is repo rted that installing Watchman 4.7.0 or n ewer fixes the issue . If you u se [Homebr ew](http:/ /brew.sh/) , you can run these commands t o update i t: | |
2370 | ||
2371 | ``` | |
2372 | watchman s hutdown-se rver | |
2373 | brew updat e | |
2374 | brew reins tall watch man | |
2375 | ``` | |
2376 | ||
2377 | You can fi nd [other installati on methods ](https:// facebook.g ithub.io/w atchman/do cs/install .html#buil d-install) on the Wa tchman doc umentation page. | |
2378 | ||
2379 | If this st ill doesnâ €™t help, try runnin g `launchc tl unload -F ~/Libra ry/LaunchA gents/com. github.fac ebook.watc hman.plist `. | |
2380 | ||
2381 | There are also repor ts that *u ninstallin g* Watchma n fixes th e issue. S o if nothi ng else he lps, remov e it from your syste m and try again. | |
2382 | ||
2383 | ### `npm r un build` exits too early | |
2384 | ||
2385 | It is repo rted that `npm run b uild` can fail on ma chines wit h limited memory and no swap s pace, whic h is commo n in cloud environme nts. Even with small projects this comma nd can inc rease RAM usage in y our system by hundre ds of mega bytes, so if you hav e less tha n 1 GB of available memory you r build is likely to fail with the follo wing messa ge: | |
2386 | ||
2387 | > The bui ld failed because th e process exited too early. Th is probabl y means th e system r an out of memory or someone ca lled `kill -9` on th e process. | |
2388 | ||
2389 | If you are completel y sure tha t you didn 't termina te the pro cess, cons ider [addi ng some sw ap space]( https://ww w.digitalo cean.com/c ommunity/t utorials/h ow-to-add- swap-on-ub untu-14-04 ) to the m achine you ’re buil ding on, o r build th e project locally. | |
2390 | ||
2391 | ### `npm r un build` fails on H eroku | |
2392 | ||
2393 | This may b e a proble m with cas e sensitiv e filename s. | |
2394 | Please ref er to [thi s section] (#resolvin g-heroku-d eployment- errors). | |
2395 | ||
2396 | ### Moment .js locale s are miss ing | |
2397 | ||
2398 | If you use a [Moment .js](https ://momentj s.com/), y ou might n otice that only the English lo cale is av ailable by default. This is be cause the locale fil es are lar ge, and yo u probably only need a subset of [all th e locales provided b y Moment.j s](https:/ /momentjs. com/#multi ple-locale -support). | |
2399 | ||
2400 | To add a s pecific Mo ment.js lo cale to yo ur bundle, you need to import it explici tly.<br> | |
2401 | For exampl e: | |
2402 | ||
2403 | ```js | |
2404 | import mom ent from ' moment'; | |
2405 | import 'mo ment/local e/fr'; | |
2406 | ``` | |
2407 | ||
2408 | If import multiple l ocales thi s way, you can later switch be tween them by callin g `moment. locale()` with the l ocale name : | |
2409 | ||
2410 | ```js | |
2411 | import mom ent from ' moment'; | |
2412 | import 'mo ment/local e/fr'; | |
2413 | import 'mo ment/local e/es'; | |
2414 | ||
2415 | // ... | |
2416 | ||
2417 | moment.loc ale('fr'); | |
2418 | ``` | |
2419 | ||
2420 | This will only work for locale s that hav e been exp licitly im ported bef ore. | |
2421 | ||
2422 | ### `npm r un build` fails to m inify | |
2423 | ||
2424 | Some third -party pac kages don' t compile their code to ES5 be fore publi shing to n pm. This o ften cause s problems in the ec osystem be cause neit her browse rs (except for most modern ver sions) nor some tool s currentl y support all ES6 fe atures. We recommend to publis h code on npm as ES5 at least for a few more years . | |
2425 | ||
2426 | <br> | |
2427 | To resolve this: | |
2428 | ||
2429 | 1. Open an issue on the depend ency's iss ue tracker and ask t hat the pa ckage be p ublished p re-compile d. | |
2430 | * Note: Create Rea ct App can consume b oth Common JS and ES modules. F or Node.js compatibi lity, it i s recommen ded that t he main en try point is CommonJ S. However , they can optionall y provide an ES modu le entry p oint with the `modul e` field i n `package .json`. No te that ** even if a library pr ovides an ES Modules version, it should still prec ompile oth er ES6 fea tures to E S5 if it i ntends to support ol der browse rs**. | |
2431 | ||
2432 | 2. Fork th e package and publis h a correc ted versio n yourself . | |
2433 | ||
2434 | 3. If the dependency is small enough, co py it to y our `src/` folder an d treat it as applic ation code . | |
2435 | ||
2436 | In the fut ure, we mi ght start automatica lly compil ing incomp atible thi rd-party m odules, bu t it is no t currentl y supporte d. This ap proach wou ld also sl ow down th e producti on builds. | |
2437 | ||
2438 | ## Alterna tives to E jecting | |
2439 | ||
2440 | [Ejecting] (#npm-run- eject) let s you cust omize anyt hing, but from that point on y ou have to maintain the config uration an d scripts yourself. This can b e daunting if you ha ve many si milar proj ects. In s uch cases instead of ejecting we recomme nd to *for k* `react- scripts` a nd any oth er package s you need . [This ar ticle](htt ps://auth0 .com/blog/ how-to-con figure-cre ate-react- app/) dive s into how to do it in depth. You can fi nd more di scussion i n [this is sue](https ://github. com/facebo okincubato r/create-r eact-app/i ssues/682) . | |
2441 | ||
2442 | ## Somethi ng Missing ? | |
2443 | ||
2444 | If you hav e ideas fo r more “ How To†recipes th at should be on this page, [le t us know] (https://g ithub.com/ facebookin cubator/cr eate-react -app/issue s) or [con tribute so me!](https ://github. com/facebo okincubato r/create-r eact-app/e dit/master /packages/ react-scri pts/templa te/README. md) |
Araxis Merge (but not the data content of this report) is Copyright © 1993-2016 Araxis Ltd (www.araxis.com). All rights reserved.