├── drupal └── .gitkeep ├── .gitignore ├── reactjs ├── .gitignore ├── src │ ├── index.css │ ├── index.js │ ├── App.test.js │ ├── App.css │ ├── App.js │ └── logo.svg ├── public │ ├── favicon.ico │ └── index.html ├── package.json └── README.md ├── docker-compose.yml ├── README.md └── LICENSE /drupal/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE files 2 | .idea 3 | -------------------------------------------------------------------------------- /reactjs/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /reactjs/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | } 6 | -------------------------------------------------------------------------------- /reactjs/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spleshka/drupal-reactjs-docker/HEAD/reactjs/public/favicon.ico -------------------------------------------------------------------------------- /reactjs/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | import './index.css'; 5 | 6 | ReactDOM.render( 7 | , 8 | document.getElementById('root') 9 | ); 10 | -------------------------------------------------------------------------------- /reactjs/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | }); 9 | -------------------------------------------------------------------------------- /reactjs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "reactjs", 3 | "version": "0.1.0", 4 | "private": true, 5 | "devDependencies": { 6 | "react-scripts": "0.9.0" 7 | }, 8 | "dependencies": { 9 | "react": "^15.4.2", 10 | "react-dom": "^15.4.2" 11 | }, 12 | "scripts": { 13 | "start": "react-scripts start", 14 | "build": "react-scripts build", 15 | "test": "react-scripts test --env=jsdom", 16 | "eject": "react-scripts eject" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /reactjs/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 80px; 8 | } 9 | 10 | .App-header { 11 | background-color: #222; 12 | height: 150px; 13 | padding: 20px; 14 | color: white; 15 | } 16 | 17 | .App-intro { 18 | font-size: large; 19 | } 20 | 21 | @keyframes App-logo-spin { 22 | from { transform: rotate(0deg); } 23 | to { transform: rotate(360deg); } 24 | } 25 | -------------------------------------------------------------------------------- /reactjs/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import logo from './logo.svg'; 3 | import './App.css'; 4 | 5 | class App extends Component { 6 | render() { 7 | return ( 8 |
9 |
10 | logo 11 |

Welcome to React

12 |
13 |

14 | To get started, edit src/App.js and save to reload. 15 |

16 |
17 | ); 18 | } 19 | } 20 | 21 | export default App; 22 | -------------------------------------------------------------------------------- /reactjs/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 16 | React App 17 | 18 | 19 |
20 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /reactjs/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | services: 3 | 4 | ########################## 5 | ### REACTJS ############## 6 | ########################## 7 | 8 | frontend: 9 | image: node:8-alpine 10 | working_dir: /app 11 | labels: 12 | - 'traefik.backend=node' 13 | - 'traefik.port=3000' 14 | - 'traefik.frontend.rule=Host:app.docker.localhost' 15 | expose: 16 | - "3000" 17 | volumes: 18 | - ./reactjs:/app 19 | # By default we tell Docker to copy files inside of ./node_modules 20 | # folder from Docker container into the host machine. 21 | # However if you're experiencing performance issues, 22 | # feel free to uncomment the line below. 23 | # - /app/node_modules 24 | command: sh -c 'npm install && npm run start' 25 | 26 | ########################## 27 | ### DRUPAL ############### 28 | ########################## 29 | 30 | # Here we use almost out of the box docker4drupal configuration. 31 | # So you can refer to their documentation for configuration. 32 | # You can add more containers for memcached, redis, varnish, solr, etc 33 | # using pre-built docker images. 34 | # https://github.com/wodby/docker4drupal/blob/master/docker-compose.yml 35 | 36 | backend_php: 37 | image: wodby/drupal-php:8-1.13 38 | # image: wodby/drupal-php:7.0-2.0.0 39 | environment: 40 | PHP_SENDMAIL_PATH: /usr/sbin/sendmail -t -i -S backend_mailhog:1025 41 | # PHP_XDEBUG: 1 42 | # PHP_XDEBUG_DEFAULT_ENABLE: 1 43 | # PHP_XDEBUG_REMOTE_CONNECT_BACK: 0 # This is needed to respect remote.host setting bellow 44 | # PHP_XDEBUG_REMOTE_HOST: "10.254.254.254" # You will also need to 'sudo ifconfig lo0 alias 10.254.254.254' 45 | volumes: 46 | - ./drupal:/var/www/html 47 | # - d4d-unison-sync:/var/www/html:rw # Replace volume to this to use docker-sync for macOS users 48 | 49 | backend_mariadb: 50 | image: wodby/mariadb:10.1-2.0.0 51 | environment: 52 | MYSQL_ROOT_PASSWORD: password 53 | MYSQL_DATABASE: drupal 54 | MYSQL_USER: drupal 55 | MYSQL_PASSWORD: drupal 56 | # command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci # The simple way to override the mariadb config. 57 | # volumes: 58 | # - ./mariadb-init:/docker-entrypoint-initdb.d # Place init .sql file(s) here. 59 | # - /path/to/mariadb/data/on/host:/var/lib/mysql # I want to manage volumes manually. 60 | 61 | backend_nginx: 62 | image: wodby/drupal-nginx:8-1.10-2.0.0 63 | restart: unless-stopped 64 | depends_on: 65 | - backend_php 66 | environment: 67 | NGINX_BACKEND_HOST: backend_php 68 | NGINX_SERVER_ROOT: /var/www/html/web 69 | volumes: 70 | - ./drupal:/var/www/html 71 | labels: 72 | - 'traefik.backend=nginx' 73 | - 'traefik.port=80' 74 | - 'traefik.frontend.rule=Host:drupal.docker.localhost' 75 | 76 | backend_pma: 77 | image: phpmyadmin/phpmyadmin 78 | environment: 79 | PMA_HOST: backend_mariadb 80 | PMA_USER: drupal 81 | PMA_PASSWORD: drupal 82 | PHP_UPLOAD_MAX_FILESIZE: 1G 83 | PHP_MAX_INPUT_VARS: 1G 84 | labels: 85 | - 'traefik.backend=pma' 86 | - 'traefik.port=80' 87 | - 'traefik.frontend.rule=Host:pma.drupal.docker.localhost' 88 | 89 | backend_mailhog: 90 | image: mailhog/mailhog 91 | labels: 92 | - 'traefik.backend=mailhog' 93 | - 'traefik.port=8025' 94 | - 'traefik.frontend.rule=Host:mailhog.drupal.docker.localhost' 95 | 96 | ########################## 97 | ### REVERSE PROXY ######## 98 | ########################## 99 | 100 | traefik: 101 | image: traefik 102 | restart: unless-stopped 103 | command: -c /dev/null --web --docker --logLevel=INFO 104 | ports: 105 | - '8000:80' 106 | - '8080:8080' 107 | volumes: 108 | - /var/run/docker.sock:/var/run/docker.sock 109 | 110 | # Docker-sync for macOS users 111 | #volumes: 112 | # d4d-unison-sync: 113 | # external: true 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Newer version is available! 2 | 3 | There's a newer version of a boilerplate avaialble at https://github.com/systemseed/drupal_reactjs_boilerplate. It has many more features & server side rendering support. 4 | 5 | # What is this project for? 6 | 7 | It's a really quick start for **LOCAL** development of ReactJS + Drupal 8 applications. 8 | 9 | As the result of configuration, you'll get: 10 | - Working and ready for development ReactJS application 11 | - Working and ready for development Drupal 8 application 12 | - UI to access Drupal database 13 | - UI to access all emails rerouted from php (apart from emails sent through SMTP) 14 | 15 | # Advantages of this project 16 | 17 | - You don't need to have `composer` on `npm` installed locally. Everything is being done though Docker containers. 18 | - You don't depend on versions of `composer` or `npm` installed at dev environments of your team members. 19 | - Docker configuration for Drupal is based on [docker4drupal](http://docker4drupal.org) containers. It provides very good flexibility for Docker-based local development. If you need more containers (i.e. for `memcached`, `redis`, `solr`, etc) - just check out what they offer. 20 | - Drupal configuration is based on [drupal-composer/drupal-project](https://github.com/drupal-composer/drupal-project) project which provides best dev experience in working with Drupal through `composer`. 21 | - ReactJS application bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app) - minimal & clean start for ReactJS development. 22 | - Human readable local host names. No more ugly `localhost:PORT` stuff. 23 | 24 | # Dependencies 25 | 26 | All you need to have is [Docker](https://docs.docker.com/engine/installation/) and [Docker Compose](https://docs.docker.com/compose/install/) installed. That's it. 27 | 28 | # Hosts 29 | 30 | At the end of configuration journey you'll get the following hosts available: 31 | 32 | | URL | Name | 33 | | -------------------------------------------- | ------------------- | 34 | | http://app.docker.localhost:8000/ | ReactJS application | 35 | | http://drupal.docker.localhost:8000/ | Drupal 8 | 36 | | http://pma.drupal.docker.localhost:8000/ | PhpMyAdmin | 37 | | http://mailhog.drupal.docker.localhost:8000/ | Mailhog | 38 | 39 | If you want, you can go further and configure `traefik` in `docker-compose.yml` file to get rid of `8000` port. 40 | As well as that, you can add custom hosts to your `/etc/hosts` file (for example, `127.0.0. 1 app.local`), reconfigure `traefik` to use these hosts in `docker-compose.yml` and eventually get beautiful URLs. 41 | 42 | # Getting started 43 | 44 | 1. Download this repo to your local machine: 45 | 46 | ``` 47 | git clone git@github.com:spleshka/drupal-reactjs-docker.git 48 | ``` 49 | 50 | 2. Bootstrap Docker containers listed in `docker-compose.yml` file: 51 | 52 | ``` 53 | docker-compose up -d 54 | ``` 55 | 56 | During the process all necessary containers will be downloaded. 57 | As well as that, `npm install` will be invoked to build ReactJS dependencies inside of Docker container. 58 | This process may take 1-2 minutes. 59 | It means that `http://app.docker.localhost:8000/` will not be reachable until that (you'll see nginx error). 60 | 61 | You DON'T need to have `npm` installed locally. 62 | 63 | 3. At this point `./drupal` folder is still empty. Let's get it fixed: 64 | 65 | ``` 66 | sudo rm drupal/.gitkeep 67 | docker-compose run backend_php composer create-project drupal-composer/drupal-project:8.x-dev . --stability dev --no-interaction -vvv 68 | ``` 69 | 70 | All we do here is downloading Drupal with its dependencies using `backend_php` container. 71 | The installation might take around 5 minutes. No worries, it's expected. 72 | Check out [Drupal Project](https://github.com/drupal-composer/drupal-project) for development guideline. 73 | 74 | You DON'T need to have `composer` installed locally. 75 | 76 | 4. It's all done now! You may try accessing any host listed in the `Hosts` section of this manual. 77 | 78 | 5. As the final step you'd probably want to commit everything to your own repository. 79 | Feel free to drop `.git` folder in the project root and initialize it with your git settings. 80 | 81 | As soon as this is done it's safe to run `git add -A` and commit everything what's been added. 82 | All files which should be ignored by git already specified in proper `.gitignore` files. 83 | 84 | ## Shutting down the environments 85 | 86 | It's **IMPORTANT** to stop Docker containers using `docker-compose stop`. 87 | 88 | Of course there's a possibility to shut the Docker containers down using `docker-compose down`, but it will drop Drupal database. 89 | You can read a little bit more about it [here](https://github.com/wodby/docker4drupal/blob/master/CHANGELOG.md#action-required-before-upgrading). 90 | 91 | ## CLI to work with ReactJS application 92 | 93 | To access all `npm` commands you can simply run shell inside of `frontend` Docker container: 94 | 95 | ``` 96 | docker-compose run frontend sh 97 | ``` 98 | 99 | Then use `npm` CLI as usual. For example, add a new package: 100 | 101 | ``` 102 | npm install lodash --save 103 | ``` 104 | 105 | All you'll need to commit is the change to `package.json` file. 106 | 107 | ## CLI to work with Drupal application 108 | 109 | To access all available CLI to manage Drupal, run shell inside of `backend_php` Docker container: 110 | 111 | ``` 112 | docker-compose run backend_php sh 113 | ``` 114 | 115 | Then run any command you need. It's possible to use `composer`, `drush`, `drupal`. 116 | 117 | If you want to run a single command inside of the container then you don't have to run shell first. Just do it this way: 118 | 119 | ``` 120 | docker-compose run backend_php composer require drupal/devel:~1.0 121 | ``` 122 | 123 | After that commit resulting `composer.json` and `composer.lock` files. 124 | 125 | Note that Drush and Drupal Console have to be invoked inside of `web` folder, so you'll have to `cd web` first. 126 | 127 | Alternatively, you might use the following command to run `drush` or `drupal` CLI outside of Docker container: 128 | 129 | ``` 130 | docker-compose run backend_php drush --root="./web/" 131 | ``` 132 | 133 | If this command seems to be too long to type every time, consider adding it to the list of your bash aliases: 134 | 135 | ``` 136 | alias dockerdrush=docker-compose run backend_php drush --root="./web/" 137 | ``` 138 | 139 | Then you'll be able to do something like this: 140 | 141 | ``` 142 | dockerdrush cr 143 | ``` 144 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /reactjs/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 2 | 3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 5 | 6 | ## Table of Contents 7 | 8 | - [Updating to New Releases](#updating-to-new-releases) 9 | - [Sending Feedback](#sending-feedback) 10 | - [Folder Structure](#folder-structure) 11 | - [Available Scripts](#available-scripts) 12 | - [npm start](#npm-start) 13 | - [npm test](#npm-test) 14 | - [npm run build](#npm-run-build) 15 | - [npm run eject](#npm-run-eject) 16 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 17 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 18 | - [Changing the Page ``](#changing-the-page-title) 19 | - [Installing a Dependency](#installing-a-dependency) 20 | - [Importing a Component](#importing-a-component) 21 | - [Adding a Stylesheet](#adding-a-stylesheet) 22 | - [Post-Processing CSS](#post-processing-css) 23 | - [Adding Images and Fonts](#adding-images-and-fonts) 24 | - [Using the `public` Folder](#using-the-public-folder) 25 | - [Changing the HTML](#changing-the-html) 26 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 27 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 28 | - [Using Global Variables](#using-global-variables) 29 | - [Adding Bootstrap](#adding-bootstrap) 30 | - [Adding Flow](#adding-flow) 31 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 32 | - [Can I Use Decorators?](#can-i-use-decorators) 33 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 34 | - [Node](#node) 35 | - [Ruby on Rails](#ruby-on-rails) 36 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 37 | - [Using HTTPS in Development](#using-https-in-development) 38 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 39 | - [Running Tests](#running-tests) 40 | - [Filename Conventions](#filename-conventions) 41 | - [Command Line Interface](#command-line-interface) 42 | - [Version Control Integration](#version-control-integration) 43 | - [Writing Tests](#writing-tests) 44 | - [Testing Components](#testing-components) 45 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 46 | - [Initializing Test Environment](#initializing-test-environment) 47 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 48 | - [Coverage Reporting](#coverage-reporting) 49 | - [Continuous Integration](#continuous-integration) 50 | - [Disabling jsdom](#disabling-jsdom) 51 | - [Snapshot Testing](#snapshot-testing) 52 | - [Editor Integration](#editor-integration) 53 | - [Developing Components in Isolation](#developing-components-in-isolation) 54 | - [Making a Progressive Web App](#making-a-progressive-web-app) 55 | - [Deployment](#deployment) 56 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 57 | - [Building for Relative Paths](#building-for-relative-paths) 58 | - [Firebase](#firebase) 59 | - [GitHub Pages](#github-pages) 60 | - [Heroku](#heroku) 61 | - [Modulus](#modulus) 62 | - [Netlify](#netlify) 63 | - [Now](#now) 64 | - [S3 and CloudFront](#s3-and-cloudfront) 65 | - [Surge](#surge) 66 | - [Advanced Configuration](#advanced-configuration) 67 | - [Troubleshooting](#troubleshooting) 68 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 69 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 70 | - [`npm run build` silently fails](#npm-run-build-silently-fails) 71 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 72 | - [Something Missing?](#something-missing) 73 | 74 | ## Updating to New Releases 75 | 76 | Create React App is divided into two packages: 77 | 78 | * `create-react-app` is a global command-line utility that you use to create new projects. 79 | * `react-scripts` is a development dependency in the generated projects (including this one). 80 | 81 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 82 | 83 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 84 | 85 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 86 | 87 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 88 | 89 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 90 | 91 | ## Sending Feedback 92 | 93 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 94 | 95 | ## Folder Structure 96 | 97 | After creation, your project should look like this: 98 | 99 | ``` 100 | my-app/ 101 | README.md 102 | node_modules/ 103 | package.json 104 | public/ 105 | index.html 106 | favicon.ico 107 | src/ 108 | App.css 109 | App.js 110 | App.test.js 111 | index.css 112 | index.js 113 | logo.svg 114 | ``` 115 | 116 | For the project to build, **these files must exist with exact filenames**: 117 | 118 | * `public/index.html` is the page template; 119 | * `src/index.js` is the JavaScript entry point. 120 | 121 | You can delete or rename the other files. 122 | 123 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 124 | You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them. 125 | 126 | Only files inside `public` can be used from `public/index.html`.<br> 127 | Read instructions below for using assets from JavaScript and HTML. 128 | 129 | You can, however, create more top-level directories.<br> 130 | They will not be included in the production build so you can use them for things like documentation. 131 | 132 | ## Available Scripts 133 | 134 | In the project directory, you can run: 135 | 136 | ### `npm start` 137 | 138 | Runs the app in the development mode.<br> 139 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 140 | 141 | The page will reload if you make edits.<br> 142 | You will also see any lint errors in the console. 143 | 144 | ### `npm test` 145 | 146 | Launches the test runner in the interactive watch mode.<br> 147 | See the section about [running tests](#running-tests) for more information. 148 | 149 | ### `npm run build` 150 | 151 | Builds the app for production to the `build` folder.<br> 152 | It correctly bundles React in production mode and optimizes the build for the best performance. 153 | 154 | The build is minified and the filenames include the hashes.<br> 155 | Your app is ready to be deployed! 156 | 157 | See the section about [deployment](#deployment) for more information. 158 | 159 | ### `npm run eject` 160 | 161 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 162 | 163 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 164 | 165 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 166 | 167 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 168 | 169 | ## Syntax Highlighting in the Editor 170 | 171 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. 172 | 173 | ## Displaying Lint Output in the Editor 174 | 175 | >Note: this feature is available with `react-scripts@0.2.0` and higher. 176 | 177 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 178 | 179 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 180 | 181 | You would need to install an ESLint plugin for your editor first. 182 | 183 | >**A note for Atom `linter-eslint` users** 184 | 185 | >If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked: 186 | 187 | ><img src="http://i.imgur.com/yVNNHJM.png" width="300"> 188 | 189 | 190 | >**For Visual Studio Code users** 191 | 192 | >VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line: 193 | 194 | >```js 195 | { 196 | // ... 197 | "extends": "react-app" 198 | } 199 | ``` 200 | 201 | Then add this block to the `package.json` file of your project: 202 | 203 | ```js 204 | { 205 | // ... 206 | "eslintConfig": { 207 | "extends": "react-app" 208 | } 209 | } 210 | ``` 211 | 212 | Finally, you will need to install some packages *globally*: 213 | 214 | ```sh 215 | npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@2.2.3 eslint-plugin-flowtype@2.21.0 216 | ``` 217 | 218 | We recognize that this is suboptimal, but it is currently required due to the way we hide the ESLint dependency. The ESLint team is already [working on a solution to this](https://github.com/eslint/eslint/issues/3458) so this may become unnecessary in a couple of months. 219 | 220 | ## Changing the Page `<title>` 221 | 222 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 223 | 224 | Note that normally you wouldn't edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. 225 | 226 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. 227 | 228 | Finally, if you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). 229 | 230 | ## Installing a Dependency 231 | 232 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: 233 | 234 | ``` 235 | npm install --save <library-name> 236 | ``` 237 | 238 | ## Importing a Component 239 | 240 | This project setup supports ES6 modules thanks to Babel.<br> 241 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. 242 | 243 | For example: 244 | 245 | ### `Button.js` 246 | 247 | ```js 248 | import React, { Component } from 'react'; 249 | 250 | class Button extends Component { 251 | render() { 252 | // ... 253 | } 254 | } 255 | 256 | export default Button; // Don’t forget to use export default! 257 | ``` 258 | 259 | ### `DangerButton.js` 260 | 261 | 262 | ```js 263 | import React, { Component } from 'react'; 264 | import Button from './Button'; // Import a component from another file 265 | 266 | class DangerButton extends Component { 267 | render() { 268 | return <Button color="red" />; 269 | } 270 | } 271 | 272 | export default DangerButton; 273 | ``` 274 | 275 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. 276 | 277 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. 278 | 279 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. 280 | 281 | Learn more about ES6 modules: 282 | 283 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) 284 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 285 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 286 | 287 | ## Adding a Stylesheet 288 | 289 | This project setup uses [Webpack](https://webpack.github.io/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: 290 | 291 | ### `Button.css` 292 | 293 | ```css 294 | .Button { 295 | padding: 20px; 296 | } 297 | ``` 298 | 299 | ### `Button.js` 300 | 301 | ```js 302 | import React, { Component } from 'react'; 303 | import './Button.css'; // Tell Webpack that Button.js uses these styles 304 | 305 | class Button extends Component { 306 | render() { 307 | // You can use them as regular CSS styles 308 | return <div className="Button" />; 309 | } 310 | } 311 | ``` 312 | 313 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 314 | 315 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. 316 | 317 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. 318 | 319 | ## Post-Processing CSS 320 | 321 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. 322 | 323 | For example, this: 324 | 325 | ```css 326 | .App { 327 | display: flex; 328 | flex-direction: row; 329 | align-items: center; 330 | } 331 | ``` 332 | 333 | becomes this: 334 | 335 | ```css 336 | .App { 337 | display: -webkit-box; 338 | display: -ms-flexbox; 339 | display: flex; 340 | -webkit-box-orient: horizontal; 341 | -webkit-box-direction: normal; 342 | -ms-flex-direction: row; 343 | flex-direction: row; 344 | -webkit-box-align: center; 345 | -ms-flex-align: center; 346 | align-items: center; 347 | } 348 | ``` 349 | 350 | There is currently no support for preprocessors such as Less, or for sharing variables across CSS files. 351 | 352 | ## Adding Images and Fonts 353 | 354 | With Webpack, using static assets like images and fonts works similarly to CSS. 355 | 356 | You can **`import` an image right in a JavaScript module**. This tells Webpack to include that image in the bundle. Unlike CSS imports, importing an image or a font gives you a string value. This value is the final image path you can reference in your code. 357 | 358 | Here is an example: 359 | 360 | ```js 361 | import React from 'react'; 362 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 363 | 364 | console.log(logo); // /logo.84287d09.png 365 | 366 | function Header() { 367 | // Import result is the URL of your image 368 | return <img src={logo} alt="Logo" />; 369 | } 370 | 371 | export default Header; 372 | ``` 373 | 374 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 375 | 376 | This works in CSS too: 377 | 378 | ```css 379 | .Logo { 380 | background-image: url(./logo.png); 381 | } 382 | ``` 383 | 384 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 385 | 386 | Please be advised that this is also a custom feature of Webpack. 387 | 388 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 389 | An alternative way of handling static assets is described in the next section. 390 | 391 | ## Using the `public` Folder 392 | 393 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 394 | 395 | ### Changing the HTML 396 | 397 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 398 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 399 | 400 | ### Adding Assets Outside of the Module System 401 | 402 | You can also add other assets to the `public` folder. 403 | 404 | Note that we normally encourage you to `import` assets in JavaScript files instead. 405 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-and-fonts). 406 | This mechanism provides a number of benefits: 407 | 408 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 409 | * Missing files cause compilation errors instead of 404 errors for your users. 410 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 411 | 412 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 413 | 414 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 415 | 416 | Inside `index.html`, you can use it like this: 417 | 418 | ```html 419 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 420 | ``` 421 | 422 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 423 | 424 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 425 | 426 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 427 | 428 | ```js 429 | render() { 430 | // Note: this is an escape hatch and should be used sparingly! 431 | // Normally we recommend using `import` for getting asset URLs 432 | // as described in “Adding Images and Fonts” above this section. 433 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 434 | } 435 | ``` 436 | 437 | Keep in mind the downsides of this approach: 438 | 439 | * None of the files in `public` folder get post-processed or minified. 440 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 441 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 442 | 443 | ### When to Use the `public` Folder 444 | 445 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-and-fonts) from JavaScript. 446 | The `public` folder is useful as a workaround for a number of less common cases: 447 | 448 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 449 | * You have thousands of images and need to dynamically reference their paths. 450 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 451 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 452 | 453 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 454 | 455 | ## Using Global Variables 456 | 457 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 458 | 459 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 460 | 461 | ```js 462 | const $ = window.$; 463 | ``` 464 | 465 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 466 | 467 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 468 | 469 | ## Adding Bootstrap 470 | 471 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 472 | 473 | Install React Bootstrap and Bootstrap from NPM. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 474 | 475 | ``` 476 | npm install react-bootstrap --save 477 | npm install bootstrap@3 --save 478 | ``` 479 | 480 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the ```src/index.js``` file: 481 | 482 | ```js 483 | import 'bootstrap/dist/css/bootstrap.css'; 484 | import 'bootstrap/dist/css/bootstrap-theme.css'; 485 | ``` 486 | 487 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 488 | 489 | ```js 490 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 491 | ``` 492 | 493 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 494 | 495 | ## Adding Flow 496 | 497 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 498 | 499 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 500 | 501 | To add Flow to a Create React App project, follow these steps: 502 | 503 | 1. Run `npm install --save-dev flow-bin`. 504 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 505 | 3. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 506 | 507 | Now you can run `npm run flow` to check the files for type errors. 508 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 509 | In the future we plan to integrate it into Create React App even more closely. 510 | 511 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 512 | 513 | ## Adding Custom Environment Variables 514 | 515 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 516 | 517 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 518 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 519 | `REACT_APP_`. 520 | 521 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). 522 | 523 | These environment variables will be defined for you on `process.env`. For example, having an environment 524 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`, in addition 525 | to `process.env.NODE_ENV`. 526 | 527 | >Note: Changing any environment variables will require you to restart the development server if it is running. 528 | 529 | These environment variables can be useful for displaying information conditionally based on where the project is 530 | deployed or consuming sensitive data that lives outside of version control. 531 | 532 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 533 | in the environment inside a `<form>`: 534 | 535 | ```jsx 536 | render() { 537 | return ( 538 | <div> 539 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 540 | <form> 541 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 542 | </form> 543 | </div> 544 | ); 545 | } 546 | ``` 547 | 548 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 549 | 550 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 551 | 552 | ```html 553 | <div> 554 | <small>You are running this application in <b>development</b> mode.</small> 555 | <form> 556 | <input type="hidden" value="abcdef" /> 557 | </form> 558 | </div> 559 | ``` 560 | 561 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 562 | 563 | ```js 564 | if (process.env.NODE_ENV !== 'production') { 565 | analytics.disable(); 566 | } 567 | ``` 568 | 569 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 570 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 571 | a `.env` file. 572 | 573 | ### Adding Temporary Environment Variables In Your Shell 574 | 575 | Defining environment variables can vary between OSes. It's also important to know that this manner is temporary for the 576 | life of the shell session. 577 | 578 | #### Windows (cmd.exe) 579 | 580 | ```cmd 581 | set REACT_APP_SECRET_CODE=abcdef&&npm start 582 | ``` 583 | 584 | (Note: the lack of whitespace is intentional.) 585 | 586 | #### Linux, macOS (Bash) 587 | 588 | ```bash 589 | REACT_APP_SECRET_CODE=abcdef npm start 590 | ``` 591 | 592 | ### Adding Development Environment Variables In `.env` 593 | 594 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 595 | 596 | To define permanent environment variables, create a file called `.env` in the root of your project: 597 | 598 | ``` 599 | REACT_APP_SECRET_CODE=abcdef 600 | ``` 601 | 602 | These variables will act as the defaults if the machine does not explicitly set them.<br> 603 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 604 | 605 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 606 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 607 | 608 | ## Can I Use Decorators? 609 | 610 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.<br> 611 | Create React App doesn’t support decorator syntax at the moment because: 612 | 613 | * It is an experimental proposal and is subject to change. 614 | * The current specification version is not officially supported by Babel. 615 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 616 | 617 | However in many cases you can rewrite decorator-based code without decorators just as fine.<br> 618 | Please refer to these two threads for reference: 619 | 620 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 621 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 622 | 623 | Create React App will add decorator support when the specification advances to a stable stage. 624 | 625 | ## Integrating with an API Backend 626 | 627 | These tutorials will help you to integrate your app with an API backend running on another port, 628 | using `fetch()` to access it. 629 | 630 | ### Node 631 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 632 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 633 | 634 | ### Ruby on Rails 635 | 636 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 637 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 638 | 639 | ## Proxying API Requests in Development 640 | 641 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 642 | 643 | People often serve the front-end React app from the same host and port as their backend implementation.<br> 644 | For example, a production setup might look like this after the app is deployed: 645 | 646 | ``` 647 | / - static server returns index.html with React app 648 | /todos - static server returns index.html with React app 649 | /api/todos - server handles any /api/* requests using the backend implementation 650 | ``` 651 | 652 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 653 | 654 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 655 | 656 | ```js 657 | "proxy": "http://localhost:4000", 658 | ``` 659 | 660 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 661 | 662 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 663 | 664 | ``` 665 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 666 | ``` 667 | 668 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 669 | 670 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.<br> 671 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 672 | 673 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 674 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 675 | 676 | ## Using HTTPS in Development 677 | 678 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 679 | 680 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 681 | 682 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 683 | 684 | #### Windows (cmd.exe) 685 | 686 | ```cmd 687 | set HTTPS=true&&npm start 688 | ``` 689 | 690 | (Note: the lack of whitespace is intentional.) 691 | 692 | #### Linux, macOS (Bash) 693 | 694 | ```bash 695 | HTTPS=true npm start 696 | ``` 697 | 698 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 699 | 700 | ## Generating Dynamic `<meta>` Tags on the Server 701 | 702 | Since Create React App doesn’t support server rendering, you might be wondering how to make `<meta>` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 703 | 704 | ```html 705 | <!doctype html> 706 | <html lang="en"> 707 | <head> 708 | <meta property="og:title" content="%OG_TITLE%"> 709 | <meta property="og:description" content="%OG_DESCRIPTION%"> 710 | ``` 711 | 712 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `%OG_TITLE%`, `%OG_DESCRIPTION%`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 713 | 714 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 715 | 716 | ## Running Tests 717 | 718 | >Note: this feature is available with `react-scripts@0.3.0` and higher.<br> 719 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 720 | 721 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 722 | 723 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 724 | 725 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 726 | 727 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 728 | 729 | ### Filename Conventions 730 | 731 | Jest will look for test files with any of the following popular naming conventions: 732 | 733 | * Files with `.js` suffix in `__tests__` folders. 734 | * Files with `.test.js` suffix. 735 | * Files with `.spec.js` suffix. 736 | 737 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 738 | 739 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 740 | 741 | ### Command Line Interface 742 | 743 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 744 | 745 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 746 | 747 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 748 | 749 | ### Version Control Integration 750 | 751 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests runs fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 752 | 753 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 754 | 755 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 756 | 757 | ### Writing Tests 758 | 759 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 760 | 761 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 762 | 763 | ```js 764 | import sum from './sum'; 765 | 766 | it('sums numbers', () => { 767 | expect(sum(1, 2)).toEqual(3); 768 | expect(sum(2, 2)).toEqual(4); 769 | }); 770 | ``` 771 | 772 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/api.html#expect-value).<br> 773 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/api.html#tobecalled) to create “spies” or mock functions. 774 | 775 | ### Testing Components 776 | 777 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 778 | 779 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 780 | 781 | ```js 782 | import React from 'react'; 783 | import ReactDOM from 'react-dom'; 784 | import App from './App'; 785 | 786 | it('renders without crashing', () => { 787 | const div = document.createElement('div'); 788 | ReactDOM.render(<App />, div); 789 | }); 790 | ``` 791 | 792 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. 793 | 794 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. 795 | 796 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). You can write a smoke test with it too: 797 | 798 | ```sh 799 | npm install --save-dev enzyme react-addons-test-utils 800 | ``` 801 | 802 | ```js 803 | import React from 'react'; 804 | import { shallow } from 'enzyme'; 805 | import App from './App'; 806 | 807 | it('renders without crashing', () => { 808 | shallow(<App />); 809 | }); 810 | ``` 811 | 812 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `<App>` and doesn’t go deeper. For example, even if `<App>` itself renders a `<Button>` that throws, this test will pass. Shallow rendering is great for isolated unit tests, but you may still want to create some full rendering tests to ensure the components integrate correctly. Enzyme supports [full rendering with `mount()`](http://airbnb.io/enzyme/docs/api/mount.html), and you can also use it for testing state changes and component lifecycle. 813 | 814 | You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testing techniques. Enzyme documentation uses Chai and Sinon for assertions but you don’t have to use them because Jest provides built-in `expect()` and `jest.fn()` for spies. 815 | 816 | Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers: 817 | 818 | ```js 819 | import React from 'react'; 820 | import { shallow } from 'enzyme'; 821 | import App from './App'; 822 | 823 | it('renders welcome message', () => { 824 | const wrapper = shallow(<App />); 825 | const welcome = <h2>Welcome to React</h2>; 826 | // expect(wrapper.contains(welcome)).to.equal(true); 827 | expect(wrapper.contains(welcome)).toEqual(true); 828 | }); 829 | ``` 830 | 831 | All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/api.html#expect-value).<br> 832 | Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below. 833 | 834 | ### Using Third Party Assertion Libraries 835 | 836 | We recommend that you use `expect()` for assertions and `jest.fn()` for spies. If you are having issues with them please [file those against Jest](https://github.com/facebook/jest/issues/new), and we’ll fix them. We intend to keep making them better for React, supporting, for example, [pretty-printing React elements as JSX](https://github.com/facebook/jest/pull/1566). 837 | 838 | However, if you are used to other libraries, such as [Chai](http://chaijs.com/) and [Sinon](http://sinonjs.org/), or if you have existing code using them that you’d like to port over, you can import them normally like this: 839 | 840 | ```js 841 | import sinon from 'sinon'; 842 | import { expect } from 'chai'; 843 | ``` 844 | 845 | and then use them in your tests like you normally do. 846 | 847 | ### Initializing Test Environment 848 | 849 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 850 | 851 | If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a `src/setupTests.js` to your project. It will be automatically executed before running your tests. 852 | 853 | For example: 854 | 855 | #### `src/setupTests.js` 856 | ```js 857 | const localStorageMock = { 858 | getItem: jest.fn(), 859 | setItem: jest.fn(), 860 | clear: jest.fn() 861 | }; 862 | global.localStorage = localStorageMock 863 | ``` 864 | 865 | ### Focusing and Excluding Tests 866 | 867 | You can replace `it()` with `xit()` to temporarily exclude a test from being executed.<br> 868 | Similarly, `fit()` lets you focus on a specific test without running any other tests. 869 | 870 | ### Coverage Reporting 871 | 872 | Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.<br> 873 | Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this: 874 | 875 | ![coverage report](http://i.imgur.com/5bFhnTS.png) 876 | 877 | Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow. 878 | 879 | ### Continuous Integration 880 | 881 | By default `npm test` runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called `CI`. 882 | 883 | When creating a build of your application with `npm run build` linter warnings are not checked by default. Like `npm test`, you can force the build to perform a linter warning check by setting the environment variable `CI`. If any warnings are encountered then the build fails. 884 | 885 | Popular CI servers already set the environment variable `CI` by default but you can do this yourself too: 886 | 887 | ### On CI servers 888 | #### Travis CI 889 | 890 | 1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page. 891 | 1. Add a `.travis.yml` file to your git repository. 892 | ``` 893 | language: node_js 894 | node_js: 895 | - 4 896 | - 6 897 | cache: 898 | directories: 899 | - node_modules 900 | script: 901 | - npm test 902 | - npm run build 903 | ``` 904 | 1. Trigger your first build with a git push. 905 | 1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed. 906 | 907 | ### On your own environment 908 | ##### Windows (cmd.exe) 909 | 910 | ```cmd 911 | set CI=true&&npm test 912 | ``` 913 | 914 | ```cmd 915 | set CI=true&&npm run build 916 | ``` 917 | 918 | (Note: the lack of whitespace is intentional.) 919 | 920 | ##### Linux, macOS (Bash) 921 | 922 | ```bash 923 | CI=true npm test 924 | ``` 925 | 926 | ```bash 927 | CI=true npm run build 928 | ``` 929 | 930 | The test command will force Jest to run tests once instead of launching the watcher. 931 | 932 | > If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows. 933 | 934 | The build command will check for linter warnings and fail if any are found. 935 | 936 | ### Disabling jsdom 937 | 938 | By default, the `package.json` of the generated project looks like this: 939 | 940 | ```js 941 | // ... 942 | "scripts": { 943 | // ... 944 | "test": "react-scripts test --env=jsdom" 945 | } 946 | ``` 947 | 948 | If you know that none of your tests depend on [jsdom](https://github.com/tmpvar/jsdom), you can safely remove `--env=jsdom`, and your tests will run faster.<br> 949 | To help you make up your mind, here is a list of APIs that **need jsdom**: 950 | 951 | * Any browser globals like `window` and `document` 952 | * [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render) 953 | * [`TestUtils.renderIntoDocument()`](https://facebook.github.io/react/docs/test-utils.html#renderintodocument) ([a shortcut](https://github.com/facebook/react/blob/34761cf9a252964abfaab6faf74d473ad95d1f21/src/test/ReactTestUtils.js#L83-L91) for the above) 954 | * [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html) 955 | 956 | In contrast, **jsdom is not needed** for the following APIs: 957 | 958 | * [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering) 959 | * [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html) 960 | 961 | Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html). 962 | 963 | ### Snapshot Testing 964 | 965 | Snapshot testing is a feature of Jest that automatically generates text snapshots of your components and saves them on the disk so if the UI output changes, you get notified without manually writing any assertions on the component output. [Read more about snapshot testing.](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html) 966 | 967 | ### Editor Integration 968 | 969 | If you use [Visual Studio Code](https://code.visualstudio.com), there is a [Jest extension](https://github.com/orta/vscode-jest) which works with Create React App out of the box. This provides a lot of IDE-like features while using a text editor: showing the status of a test run with potential fail messages inline, starting and stopping the watcher automatically, and offering one-click snapshot updates. 970 | 971 | ![VS Code Jest Preview](https://cloud.githubusercontent.com/assets/49038/20795349/a032308a-b7c8-11e6-9b34-7eeac781003f.png) 972 | 973 | ## Developing Components in Isolation 974 | 975 | Usually, in an app, you have a lot of UI components, and each of them has many different states. 976 | For an example, a simple button component could have following states: 977 | 978 | * With a text label. 979 | * With an emoji. 980 | * In the disabled mode. 981 | 982 | Usually, it’s hard to see these states without running a sample app or some examples. 983 | 984 | Create React App doesn't include any tools for this by default, but you can easily add [React Storybook](https://github.com/kadirahq/react-storybook) to your project. **It is a third-party tool that lets you develop components and see all their states in isolation from your app**. 985 | 986 | ![React Storybook Demo](http://i.imgur.com/7CIAWpB.gif) 987 | 988 | You can also deploy your Storybook as a static app. This way, everyone in your team can view and review different states of UI components without starting a backend server or creating an account in your app. 989 | 990 | **Here’s how to setup your app with Storybook:** 991 | 992 | First, install the following npm package globally: 993 | 994 | ```sh 995 | npm install -g getstorybook 996 | ``` 997 | 998 | Then, run the following command inside your app’s directory: 999 | 1000 | ```sh 1001 | getstorybook 1002 | ``` 1003 | 1004 | After that, follow the instructions on the screen. 1005 | 1006 | Learn more about React Storybook: 1007 | 1008 | * Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook) 1009 | * [GitHub Repo](https://github.com/kadirahq/react-storybook) 1010 | * [Documentation](https://getstorybook.io/docs) 1011 | * [Snapshot Testing](https://github.com/kadirahq/storyshots) with React Storybook 1012 | 1013 | ## Making a Progressive Web App 1014 | 1015 | You can turn your React app into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) by following the steps in [this repository](https://github.com/jeffposnick/create-react-pwa). 1016 | 1017 | ## Deployment 1018 | 1019 | `npm run build` creates a `build` directory with a production build of your app. Set up your favourite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main.<hash>.js` are served with the contents of the `/static/js/main.<hash>.js` file. For example, Python contains a built-in HTTP server that can serve static files: 1020 | 1021 | ```sh 1022 | cd build 1023 | python -m SimpleHTTPServer 9000 1024 | ``` 1025 | 1026 | If you're using [Node](https://nodejs.org/) and [Express](http://expressjs.com/) as a server, it might look like this: 1027 | 1028 | ```javascript 1029 | const express = require('express'); 1030 | const path = require('path'); 1031 | const app = express(); 1032 | 1033 | app.use(express.static('./build')); 1034 | 1035 | app.get('/', function (req, res) { 1036 | res.sendFile(path.join(__dirname, './build', 'index.html')); 1037 | }); 1038 | 1039 | app.listen(9000); 1040 | ``` 1041 | 1042 | Create React App is not opinionated about your choice of web server. Any static file server will do. The `build` folder with static assets is the only output produced by Create React App. 1043 | 1044 | However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like `/todos/42` in your single-page app. 1045 | 1046 | ### Serving Apps with Client-Side Routing 1047 | 1048 | If you use routers that use the HTML5 [`pushState` history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) under the hood (for example, [React Router](https://github.com/ReactTraining/react-router) with `browserHistory`), many static file servers will fail. For example, if you used React Router with a route for `/todos/42`, the development server will respond to `localhost:3000/todos/42` properly, but an Express serving a production build as above will not. 1049 | 1050 | This is because when there is a fresh page load for a `/todos/42`, the server looks for the file `build/todos/42` and does not find it. The server needs to be configured to respond to a request to `/todos/42` by serving `index.html`. For example, we can amend our Express example above to serve `index.html` for any unknown paths: 1051 | 1052 | ```diff 1053 | app.use(express.static('./build')); 1054 | 1055 | -app.get('/', function (req, res) { 1056 | +app.get('/*', function (req, res) { 1057 | res.sendFile(path.join(__dirname, './build', 'index.html')); 1058 | }); 1059 | ``` 1060 | 1061 | Now requests to `/todos/42` will be handled correctly both in development and in production. 1062 | 1063 | ### Building for Relative Paths 1064 | 1065 | By default, Create React App produces a build assuming your app is hosted at the server root.<br> 1066 | To override this, specify the `homepage` in your `package.json`, for example: 1067 | 1068 | ```js 1069 | "homepage": "http://mywebsite.com/relativepath", 1070 | ``` 1071 | 1072 | This will let Create React App correctly infer the root path to use in the generated HTML file. 1073 | 1074 | #### Serving the Same Build from Different Paths 1075 | 1076 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 1077 | 1078 | If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`: 1079 | 1080 | ```js 1081 | "homepage": ".", 1082 | ``` 1083 | 1084 | This will make sure that all the asset paths are relative to `index.html`. You will then be able to move your app from `http://mywebsite.com` to `http://mywebsite.com/relativepath` or even `http://mywebsite.com/relative/path` without having to rebuild it. 1085 | 1086 | ### Firebase 1087 | 1088 | Install the Firebase CLI if you haven't already by running `npm install -g firebase-tools`. Sign up for a [Firebase account](https://console.firebase.google.com/) and create a new project. Run `firebase login` and login with your previous created Firebase account. 1089 | 1090 | Then run the `firebase init` command from your project's root. You need to choose the **Hosting: Configure and deploy Firebase Hosting sites** and choose the Firebase project you created in the previous step. You will need to agree with `database.rules.json` being created, choose `build` as the public directory, and also agree to **Configure as a single-page app** by replying with `y`. 1091 | 1092 | ```sh 1093 | === Project Setup 1094 | 1095 | First, let's associate this project directory with a Firebase project. 1096 | You can create multiple project aliases by running firebase use --add, 1097 | but for now we'll just set up a default project. 1098 | 1099 | ? What Firebase project do you want to associate as default? Example app (example-app-fd690) 1100 | 1101 | === Database Setup 1102 | 1103 | Firebase Realtime Database Rules allow you to define how your data should be 1104 | structured and when your data can be read from and written to. 1105 | 1106 | ? What file should be used for Database Rules? database.rules.json 1107 | ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json. 1108 | Future modifications to database.rules.json will update Database Rules when you run 1109 | firebase deploy. 1110 | 1111 | === Hosting Setup 1112 | 1113 | Your public directory is the folder (relative to your project directory) that 1114 | will contain Hosting assets to uploaded with firebase deploy. If you 1115 | have a build process for your assets, use your build's output directory. 1116 | 1117 | ? What do you want to use as your public directory? build 1118 | ? Configure as a single-page app (rewrite all urls to /index.html)? Yes 1119 | ✔ Wrote build/index.html 1120 | 1121 | i Writing configuration info to firebase.json... 1122 | i Writing project information to .firebaserc... 1123 | 1124 | ✔ Firebase initialization complete! 1125 | ``` 1126 | 1127 | Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`. 1128 | 1129 | ```sh 1130 | === Deploying to 'example-app-fd690'... 1131 | 1132 | i deploying database, hosting 1133 | ✔ database: rules ready to deploy. 1134 | i hosting: preparing build directory for upload... 1135 | Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully 1136 | ✔ hosting: 8 files uploaded successfully 1137 | i starting release process (may take several minutes)... 1138 | 1139 | ✔ Deploy complete! 1140 | 1141 | Project Console: https://console.firebase.google.com/project/example-app-fd690/overview 1142 | Hosting URL: https://example-app-fd690.firebaseapp.com 1143 | ``` 1144 | 1145 | For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup). 1146 | 1147 | ### GitHub Pages 1148 | 1149 | >Note: this feature is available with `react-scripts@0.2.0` and higher. 1150 | 1151 | #### Step 1: Add `homepage` to `package.json` 1152 | 1153 | **The step below is important!**<br> 1154 | **If you skip it, your app will not deploy correctly.** 1155 | 1156 | Open your `package.json` and add a `homepage` field: 1157 | 1158 | ```js 1159 | "homepage": "https://myusername.github.io/my-app", 1160 | ``` 1161 | 1162 | Create React App uses the `homepage` field to determine the root URL in the built HTML file. 1163 | 1164 | #### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json` 1165 | 1166 | Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages. 1167 | 1168 | To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run: 1169 | 1170 | ```sh 1171 | npm install --save-dev gh-pages 1172 | ``` 1173 | 1174 | Add the following scripts in your `package.json`: 1175 | 1176 | ```js 1177 | // ... 1178 | "scripts": { 1179 | // ... 1180 | "predeploy": "npm run build", 1181 | "deploy": "gh-pages -d build" 1182 | } 1183 | ``` 1184 | 1185 | The `predeploy` script will run automatically before `deploy` is run. 1186 | 1187 | #### Step 3: Deploy the site by running `npm run deploy` 1188 | 1189 | Then run: 1190 | 1191 | ```sh 1192 | npm run deploy 1193 | ``` 1194 | 1195 | #### Step 4: Ensure your project's settings use `gh-pages` 1196 | 1197 | Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch: 1198 | 1199 | <img src="http://i.imgur.com/HUjEr9l.png" width="500" alt="gh-pages branch setting"> 1200 | 1201 | #### Step 5: Optionally, configure the domain 1202 | 1203 | You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder. 1204 | 1205 | #### Notes on client-side routing 1206 | 1207 | GitHub Pages doesn't support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions: 1208 | 1209 | * You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to `hashHistory` for this effect, but the URL will be longer and more verbose (for example, `http://user.github.io/todomvc/#/todos/42?_k=yknaj`). [Read more](https://github.com/reactjs/react-router/blob/master/docs/guides/Histories.md#histories) about different history implementations in React Router. 1210 | * Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your `index.html` page with a special redirect parameter. You would need to add a `404.html` file with the redirection code to the `build` folder before deploying your project, and you’ll need to add code handling the redirect parameter to `index.html`. You can find a detailed explanation of this technique [in this guide](https://github.com/rafrex/spa-github-pages). 1211 | 1212 | ### Heroku 1213 | 1214 | Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).<br> 1215 | You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration). 1216 | 1217 | #### Resolving "Module not found: Error: Cannot resolve 'file' or 'directory'" 1218 | 1219 | Sometimes `npm run build` works locally but fails during deploy via Heroku with an error like this: 1220 | 1221 | ``` 1222 | remote: Failed to create a production build. Reason: 1223 | remote: Module not found: Error: Cannot resolve 'file' or 'directory' 1224 | MyDirectory in /tmp/build_1234/src 1225 | ``` 1226 | 1227 | This means you need to ensure that the lettercase of the file or directory you `import` matches the one you see on your filesystem or on GitHub. 1228 | 1229 | This is important because Linux (the operating system used by Heroku) is case sensitive. So `MyDirectory` and `mydirectory` are two distinct directories and thus, even though the project builds locally, the difference in case breaks the `import` statements on Heroku remotes. 1230 | 1231 | ### Modulus 1232 | 1233 | See the [Modulus blog post](http://blog.modulus.io/deploying-react-apps-on-modulus) on how to deploy your react app to Modulus. 1234 | 1235 | ## Netlify 1236 | 1237 | **To do a manual deploy to Netlify's CDN:** 1238 | 1239 | ```sh 1240 | npm install netlify-cli 1241 | netlify deploy 1242 | ``` 1243 | 1244 | Choose `build` as the path to deploy. 1245 | 1246 | **To setup continuous delivery:** 1247 | 1248 | With this setup Netlify will build and deploy when you push to git or open a pull request: 1249 | 1250 | 1. [Start a new netlify project](https://app.netlify.com/signup) 1251 | 2. Pick your Git hosting service and select your repository 1252 | 3. Click `Build your site` 1253 | 1254 | **Support for client-side routing:** 1255 | 1256 | To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules: 1257 | 1258 | ``` 1259 | /* /index.html 200 1260 | ``` 1261 | 1262 | When you build the project, Create React App will place the `public` folder contents into the build output. 1263 | 1264 | ### Now 1265 | 1266 | See [this example](https://github.com/xkawi/create-react-app-now) for a zero-configuration single-command deployment with [now](https://zeit.co/now). 1267 | 1268 | ### S3 and CloudFront 1269 | 1270 | See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-to-s3-or-cloudfront-48dae4ce0af) on how to deploy your React app to Amazon Web Services [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/). 1271 | 1272 | ### Surge 1273 | 1274 | Install the Surge CLI if you haven't already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account. You just need to specify the *build* folder and your custom domain, and you are done. 1275 | 1276 | ```sh 1277 | email: email@domain.com 1278 | password: ******** 1279 | project path: /path/to/project/build 1280 | size: 7 files, 1.8 MB 1281 | domain: create-react-app.surge.sh 1282 | upload: [====================] 100%, eta: 0.0s 1283 | propagate on CDN: [====================] 100% 1284 | plan: Free 1285 | users: email@domain.com 1286 | IP Address: X.X.X.X 1287 | 1288 | Success! Project is published and running at create-react-app.surge.sh 1289 | ``` 1290 | 1291 | Note that in order to support routers that use HTML5 `pushState` API, you may want to rename the `index.html` in your build folder to `200.html` before deploying to Surge. This [ensures that every URL falls back to that file](https://surge.sh/help/adding-a-200-page-for-client-side-routing). 1292 | 1293 | ## Advanced Configuration 1294 | 1295 | You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env). 1296 | 1297 | Variable | Development | Production | Usage 1298 | :--- | :---: | :---: | :--- 1299 | BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. 1300 | HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host. 1301 | PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port. 1302 | HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode. 1303 | PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. 1304 | CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. 1305 | 1306 | ## Troubleshooting 1307 | 1308 | ### `npm start` doesn’t detect changes 1309 | 1310 | When you save a file while `npm start` is running, the browser should refresh with the updated code.<br> 1311 | If this doesn’t happen, try one of the following workarounds: 1312 | 1313 | * If your project is in a Dropbox folder, try moving it out. 1314 | * If the watcher doesn’t see a file called `index.js` and you’re referencing it by the folder name, you [need to restart the watcher](https://github.com/facebookincubator/create-react-app/issues/1164) due to a Webpack bug. 1315 | * Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in [“Working with editors supporting safe write”](https://webpack.github.io/docs/webpack-dev-server.html#working-with-editors-ides-supporting-safe-write). 1316 | * If your project path contains parentheses, try moving the project to a path without them. This is caused by a [Webpack watcher bug](https://github.com/webpack/watchpack/issues/42). 1317 | * On Linux and macOS, you might need to [tweak system settings](https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers) to allow more watchers. 1318 | 1319 | If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659). 1320 | 1321 | ### `npm test` hangs on macOS Sierra 1322 | 1323 | If you run `npm test` and the console gets stuck after printing `react-scripts test --env=jsdom` to the console there might be a problem with your [Watchman](https://facebook.github.io/watchman/) installation as described in [facebookincubator/create-react-app#713](https://github.com/facebookincubator/create-react-app/issues/713). 1324 | 1325 | We recommend deleting `node_modules` in your project and running `npm install` (or `yarn` if you use it) first. If it doesn't help, you can try one of the numerous workarounds mentioned in these issues: 1326 | 1327 | * [facebook/jest#1767](https://github.com/facebook/jest/issues/1767) 1328 | * [facebook/watchman#358](https://github.com/facebook/watchman/issues/358) 1329 | * [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259) 1330 | 1331 | It is reported that installing Watchman 4.7.0 or newer fixes the issue. If you use [Homebrew](http://brew.sh/), you can run these commands to update it: 1332 | 1333 | ``` 1334 | watchman shutdown-server 1335 | brew update 1336 | brew reinstall watchman 1337 | ``` 1338 | 1339 | You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page. 1340 | 1341 | If this still doesn't help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`. 1342 | 1343 | There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again. 1344 | 1345 | ### `npm run build` silently fails 1346 | 1347 | It is reported that `npm run build` can fail on machines with no swap space, which is common in cloud environments. If [the symptoms are matching](https://github.com/facebookincubator/create-react-app/issues/1133#issuecomment-264612171), consider adding some swap space to the machine you’re building on, or build the project locally. 1348 | 1349 | ### `npm run build` fails on Heroku 1350 | 1351 | This may be a problem with case sensitive filenames. 1352 | Please refer to [this section](#resolving-module-not-found-error-cannot-resolve-file-or-directory). 1353 | 1354 | ## Something Missing? 1355 | 1356 | If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebookincubator/create-react-app/issues) or [contribute some!](https://github.com/facebookincubator/create-react-app/edit/master/packages/react-scripts/template/README.md) 1357 | --------------------------------------------------------------------------------