├── LICENSE
├── README.md
├── policies
└── data-source-policy.json
├── quizbiz
├── .env
├── .gitignore
├── README.md
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
│ ├── App.js
│ ├── components
│ ├── Question.js
│ ├── QuestionForm.js
│ ├── Quiz.js
│ ├── QuizInput.js
│ └── QuizPicker.js
│ ├── index.css
│ ├── index.js
│ └── serviceWorker.js
└── schemas
├── application-schema.graphql
├── list-questions.vtl.txt
├── resolver-create-question.vtl.txt
├── resolver-get-question-by-id.vtl.txt
├── simple-mutations.graphql
├── simple-query.graphql
└── test-queries.graphql
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 A Cloud Guru
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Course_Introduction_to_AWS_AppSync
2 | Learn to make the best use of managed services to build a GraphQL API
3 |
4 | IMPORTANT
5 | These files are distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
6 |
--------------------------------------------------------------------------------
/policies/data-source-policy.json:
--------------------------------------------------------------------------------
1 | {
2 | "Version": "2012-10-17",
3 | "Statement": [
4 | {
5 | "Sid": "QuizBizQuestionTable",
6 | "Effect": "Allow",
7 | "Action": [
8 | "dynamodb:BatchGetItem",
9 | "dynamodb:BatchWriteItem",
10 | "dynamodb:PutItem",
11 | "dynamodb:DeleteItem",
12 | "dynamodb:GetItem",
13 | "dynamodb:Scan",
14 | "dynamodb:Query",
15 | "dynamodb:UpdateItem"
16 | ],
17 | "Resource": [
18 | "arn:aws:dynamodb:*:*:table/QuizBizQuestion",
19 | "arn:aws:dynamodb:*:*:table/QuizBizQuestion/*",
20 | "arn:aws:dynamodb:*:*:table/QuizBizQuestions",
21 | "arn:aws:dynamodb:*:*:table/QuizBizQuestions/*"
22 | ]
23 | }
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/quizbiz/.env:
--------------------------------------------------------------------------------
1 | SKIP_PREFLIGHT_CHECK=true
2 |
--------------------------------------------------------------------------------
/quizbiz/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 | .amplifyrc
3 | /amplify
4 | src/aws-exports.js
5 |
6 | # dependencies
7 | /node_modules
8 |
9 | # testing
10 | /coverage
11 |
12 | # production
13 | /build
14 |
15 | # misc
16 | .DS_Store
17 | .env.local
18 | .env.development.local
19 | .env.test.local
20 | .env.production.local
21 |
22 | npm-debug.log*
23 | yarn-debug.log*
24 | yarn-error.log*
25 |
--------------------------------------------------------------------------------
/quizbiz/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md).
5 |
6 | ## Table of Contents
7 |
8 | - [Updating to New Releases](#updating-to-new-releases)
9 | - [Sending Feedback](#sending-feedback)
10 | - [Folder Structure](#folder-structure)
11 | - [Available Scripts](#available-scripts)
12 | - [npm start](#npm-start)
13 | - [npm test](#npm-test)
14 | - [npm run build](#npm-run-build)
15 | - [npm run eject](#npm-run-eject)
16 | - [Supported Browsers](#supported-browsers)
17 | - [Supported Language Features](#supported-language-features)
18 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
19 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
20 | - [Debugging in the Editor](#debugging-in-the-editor)
21 | - [Formatting Code Automatically](#formatting-code-automatically)
22 | - [Changing the Page `
`](#changing-the-page-title)
23 | - [Installing a Dependency](#installing-a-dependency)
24 | - [Importing a Component](#importing-a-component)
25 | - [Code Splitting](#code-splitting)
26 | - [Adding a Stylesheet](#adding-a-stylesheet)
27 | - [Adding a CSS Modules Stylesheet](#adding-a-css-modules-stylesheet)
28 | - [Adding a Sass Stylesheet](#adding-a-sass-stylesheet)
29 | - [Post-Processing CSS](#post-processing-css)
30 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
31 | - [Adding SVGs](#adding-svgs)
32 | - [Using the `public` Folder](#using-the-public-folder)
33 | - [Changing the HTML](#changing-the-html)
34 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
35 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
36 | - [Using Global Variables](#using-global-variables)
37 | - [Adding Bootstrap](#adding-bootstrap)
38 | - [Using a Custom Theme](#using-a-custom-theme)
39 | - [Adding Flow](#adding-flow)
40 | - [Adding Relay](#adding-relay)
41 | - [Adding a Router](#adding-a-router)
42 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
43 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
44 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
45 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
46 | - [Can I Use Decorators?](#can-i-use-decorators)
47 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests)
48 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
49 | - [Node](#node)
50 | - [Ruby on Rails](#ruby-on-rails)
51 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
52 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
53 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
54 | - [Using HTTPS in Development](#using-https-in-development)
55 | - [Generating Dynamic ` ` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
56 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
57 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
58 | - [Running Tests](#running-tests)
59 | - [Filename Conventions](#filename-conventions)
60 | - [Command Line Interface](#command-line-interface)
61 | - [Version Control Integration](#version-control-integration)
62 | - [Writing Tests](#writing-tests)
63 | - [Testing Components](#testing-components)
64 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
65 | - [Initializing Test Environment](#initializing-test-environment)
66 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
67 | - [Coverage Reporting](#coverage-reporting)
68 | - [Continuous Integration](#continuous-integration)
69 | - [Disabling jsdom](#disabling-jsdom)
70 | - [Snapshot Testing](#snapshot-testing)
71 | - [Editor Integration](#editor-integration)
72 | - [Debugging Tests](#debugging-tests)
73 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome)
74 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code)
75 | - [Developing Components in Isolation](#developing-components-in-isolation)
76 | - [Getting Started with Storybook](#getting-started-with-storybook)
77 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
78 | - [Publishing Components to npm](#publishing-components-to-npm)
79 | - [Making a Progressive Web App](#making-a-progressive-web-app)
80 | - [Why Opt-in?](#why-opt-in)
81 | - [Offline-First Considerations](#offline-first-considerations)
82 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
83 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
84 | - [Deployment](#deployment)
85 | - [Static Server](#static-server)
86 | - [Other Solutions](#other-solutions)
87 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
88 | - [Building for Relative Paths](#building-for-relative-paths)
89 | - [Customizing Environment Variables for Arbitrary Build Environments](#customizing-environment-variables-for-arbitrary-build-environments)
90 | - [Azure](#azure)
91 | - [Firebase](#firebase)
92 | - [GitHub Pages](#github-pages)
93 | - [Heroku](#heroku)
94 | - [Netlify](#netlify)
95 | - [Now](#now)
96 | - [S3 and CloudFront](#s3-and-cloudfront)
97 | - [Surge](#surge)
98 | - [Advanced Configuration](#advanced-configuration)
99 | - [Troubleshooting](#troubleshooting-1)
100 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
101 | - [`npm test` hangs or crashes on macOS Sierra](#npm-test-hangs-or-crashes-on-macos-sierra)
102 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
103 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
104 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
105 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
106 | - [Alternatives to Ejecting](#alternatives-to-ejecting)
107 | - [Something Missing?](#something-missing)
108 |
109 | ## Updating to New Releases
110 |
111 | Create React App is divided into two packages:
112 |
113 | - `create-react-app` is a global command-line utility that you use to create new projects.
114 | - `react-scripts` is a development dependency in the generated projects (including this one).
115 |
116 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
117 |
118 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
119 |
120 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
121 |
122 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` (or `yarn install`) in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
123 |
124 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
125 |
126 | ## Sending Feedback
127 |
128 | We are always open to [your feedback](https://github.com/facebook/create-react-app/issues).
129 |
130 | ## Folder Structure
131 |
132 | After creation, your project should look like this:
133 |
134 | ```
135 | my-app/
136 | README.md
137 | node_modules/
138 | package.json
139 | public/
140 | index.html
141 | favicon.ico
142 | src/
143 | App.css
144 | App.js
145 | App.test.js
146 | index.css
147 | index.js
148 | logo.svg
149 | ```
150 |
151 | For the project to build, **these files must exist with exact filenames**:
152 |
153 | - `public/index.html` is the page template;
154 | - `src/index.js` is the JavaScript entry point.
155 |
156 | You can delete or rename the other files.
157 |
158 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
159 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
160 |
161 | Only files inside `public` can be used from `public/index.html`.
162 | Read instructions below for using assets from JavaScript and HTML.
163 |
164 | You can, however, create more top-level directories.
165 | They will not be included in the production build so you can use them for things like documentation.
166 |
167 | If you have Git installed and your project is not part of a larger repository, then a new repository will be initialized resulting in an additional `.git/` top-level directory.
168 |
169 | ## Available Scripts
170 |
171 | In the project directory, you can run:
172 |
173 | ### `npm start`
174 |
175 | Runs the app in the development mode.
176 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
177 |
178 | The page will reload if you make edits.
179 | You will also see any lint errors in the console.
180 |
181 | ### `npm test`
182 |
183 | Launches the test runner in the interactive watch mode.
184 | See the section about [running tests](#running-tests) for more information.
185 |
186 | ### `npm run build`
187 |
188 | Builds the app for production to the `build` folder.
189 | It correctly bundles React in production mode and optimizes the build for the best performance.
190 |
191 | The build is minified and the filenames include the hashes.
192 | Your app is ready to be deployed!
193 |
194 | See the section about [deployment](#deployment) for more information.
195 |
196 | ### `npm run eject`
197 |
198 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
199 |
200 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
201 |
202 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
203 |
204 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
205 |
206 | ## Supported Browsers
207 |
208 | By default, the generated project supports all modern browsers.
209 | Support for Internet Explorer 9, 10, and 11 requires [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md).
210 |
211 | ### Supported Language Features
212 |
213 | This project supports a superset of the latest JavaScript standard.
214 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
215 |
216 | - [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
217 | - [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
218 | - [Object Rest/Spread Properties](https://github.com/tc39/proposal-object-rest-spread) (ES2018).
219 | - [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
220 | - [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
221 | - [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flow.org/) syntax.
222 |
223 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
224 |
225 | While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.
226 |
227 | Note that **this project includes no [polyfills](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md)** by default.
228 |
229 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are [including the appropriate polyfills manually](https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md), or that the browsers you are targeting already support them.
230 |
231 | ## Syntax Highlighting in the Editor
232 |
233 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered.
234 |
235 | ## Displaying Lint Output in the Editor
236 |
237 | > Note: this feature is available with `react-scripts@0.2.0` and higher.
238 | > It also only works with npm 3 or higher.
239 |
240 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
241 |
242 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.
243 |
244 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
245 |
246 | ```js
247 | {
248 | "extends": "react-app"
249 | }
250 | ```
251 |
252 | Now your editor should report the linting warnings.
253 |
254 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.
255 |
256 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
257 |
258 | ## Debugging in the Editor
259 |
260 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
261 |
262 | Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.
263 |
264 | ### Visual Studio Code
265 |
266 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed.
267 |
268 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
269 |
270 | ```json
271 | {
272 | "version": "0.2.0",
273 | "configurations": [
274 | {
275 | "name": "Chrome",
276 | "type": "chrome",
277 | "request": "launch",
278 | "url": "http://localhost:3000",
279 | "webRoot": "${workspaceRoot}/src",
280 | "sourceMapPathOverrides": {
281 | "webpack:///src/*": "${webRoot}/*"
282 | }
283 | }
284 | ]
285 | }
286 | ```
287 |
288 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
289 |
290 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
291 |
292 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting).
293 |
294 | ### WebStorm
295 |
296 | You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed.
297 |
298 | In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration.
299 |
300 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
301 |
302 | Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm.
303 |
304 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
305 |
306 | ## Formatting Code Automatically
307 |
308 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/).
309 |
310 | To format our code whenever we make a commit in git, we need to install the following dependencies:
311 |
312 | ```sh
313 | npm install --save husky lint-staged prettier
314 | ```
315 |
316 | Alternatively you may use `yarn`:
317 |
318 | ```sh
319 | yarn add husky lint-staged prettier
320 | ```
321 |
322 | - `husky` makes it easy to use githooks as if they are npm scripts.
323 | - `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
324 | - `prettier` is the JavaScript formatter we will run before commits.
325 |
326 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
327 |
328 | Add the following field to the `package.json` section:
329 |
330 | ```diff
331 | + "husky": {
332 | + "hooks": {
333 | + "pre-commit": "lint-staged"
334 | + }
335 | + }
336 | ```
337 |
338 | Next we add a 'lint-staged' field to the `package.json`, for example:
339 |
340 | ```diff
341 | "dependencies": {
342 | // ...
343 | },
344 | + "lint-staged": {
345 | + "src/**/*.{js,jsx,json,css}": [
346 | + "prettier --single-quote --write",
347 | + "git add"
348 | + ]
349 | + },
350 | "scripts": {
351 | ```
352 |
353 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time.
354 |
355 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page.
356 |
357 | ## Changing the Page ``
358 |
359 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
360 |
361 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML.
362 |
363 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library.
364 |
365 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files).
366 |
367 | ## Installing a Dependency
368 |
369 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`:
370 |
371 | ```sh
372 | npm install --save react-router-dom
373 | ```
374 |
375 | Alternatively you may use `yarn`:
376 |
377 | ```sh
378 | yarn add react-router-dom
379 | ```
380 |
381 | This works for any library, not just `react-router-dom`.
382 |
383 | ## Importing a Component
384 |
385 | This project setup supports ES6 modules thanks to Webpack.
386 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
387 |
388 | For example:
389 |
390 | ### `Button.js`
391 |
392 | ```js
393 | import React, { Component } from 'react';
394 |
395 | class Button extends Component {
396 | render() {
397 | // ...
398 | }
399 | }
400 |
401 | export default Button; // Don’t forget to use export default!
402 | ```
403 |
404 | ### `DangerButton.js`
405 |
406 | ```js
407 | import React, { Component } from 'react';
408 | import Button from './Button'; // Import a component from another file
409 |
410 | class DangerButton extends Component {
411 | render() {
412 | return ;
413 | }
414 | }
415 |
416 | export default DangerButton;
417 | ```
418 |
419 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
420 |
421 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
422 |
423 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
424 |
425 | Learn more about ES6 modules:
426 |
427 | - [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
428 | - [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
429 | - [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
430 |
431 | ## Code Splitting
432 |
433 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
434 |
435 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module.
436 |
437 | Here is an example:
438 |
439 | ### `moduleA.js`
440 |
441 | ```js
442 | const moduleA = 'Hello';
443 |
444 | export { moduleA };
445 | ```
446 |
447 | ### `App.js`
448 |
449 | ```js
450 | import React, { Component } from 'react';
451 |
452 | class App extends Component {
453 | handleClick = () => {
454 | import('./moduleA')
455 | .then(({ moduleA }) => {
456 | // Use moduleA
457 | })
458 | .catch(err => {
459 | // Handle failure
460 | });
461 | };
462 |
463 | render() {
464 | return (
465 |
466 | Load
467 |
468 | );
469 | }
470 | }
471 |
472 | export default App;
473 | ```
474 |
475 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
476 |
477 | You can also use it with `async` / `await` syntax if you prefer it.
478 |
479 | ### With React Router
480 |
481 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app).
482 |
483 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation.
484 |
485 | ## Adding a Stylesheet
486 |
487 | This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
488 |
489 | ### `Button.css`
490 |
491 | ```css
492 | .Button {
493 | padding: 20px;
494 | }
495 | ```
496 |
497 | ### `Button.js`
498 |
499 | ```js
500 | import React, { Component } from 'react';
501 | import './Button.css'; // Tell Webpack that Button.js uses these styles
502 |
503 | class Button extends Component {
504 | render() {
505 | // You can use them as regular CSS styles
506 | return
;
507 | }
508 | }
509 | ```
510 |
511 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-blog/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack.
512 |
513 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output.
514 |
515 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool.
516 |
517 | ## Adding a CSS Modules Stylesheet
518 |
519 | > Note: this feature is available with `react-scripts@2.0.0` and higher.
520 |
521 | This project supports [CSS Modules](https://github.com/css-modules/css-modules) alongside regular stylesheets using the `[name].module.css` file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format `[filename]\_[classname]\_\_[hash]`.
522 |
523 | > **Tip:** Should you want to preprocess a stylesheet with Sass then make sure to [follow the installation instructions](#adding-a-sass-stylesheet) and then change the stylesheet file extension as follows: `[name].module.scss` or `[name].module.sass`.
524 |
525 | CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules [here](https://css-tricks.com/css-modules-part-1-need/).
526 |
527 | ### `Button.module.css`
528 |
529 | ```css
530 | .error {
531 | background-color: red;
532 | }
533 | ```
534 |
535 | ### `another-stylesheet.css`
536 |
537 | ```css
538 | .error {
539 | color: red;
540 | }
541 | ```
542 |
543 | ### `Button.js`
544 |
545 | ```js
546 | import React, { Component } from 'react';
547 | import styles from './Button.module.css'; // Import css modules stylesheet as styles
548 | import './another-stylesheet.css'; // Import regular stylesheet
549 |
550 | class Button extends Component {
551 | render() {
552 | // reference as a js object
553 | return Error Button ;
554 | }
555 | }
556 | ```
557 |
558 | ### Result
559 |
560 | No clashes from other `.error` class names
561 |
562 | ```html
563 |
564 |
565 | ```
566 |
567 | **This is an optional feature.** Regular ` ` stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the `.module.css` extension.
568 |
569 | ## Adding a Sass Stylesheet
570 |
571 | > Note: this feature is available with `react-scripts@2.0.0` and higher.
572 |
573 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `` and `` components, we recommend creating a `` component with its own `.Button` styles, that both `` and `` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)).
574 |
575 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable.
576 |
577 | To use Sass, first install `node-sass`:
578 |
579 | ```bash
580 | $ npm install node-sass --save
581 | $ # or
582 | $ yarn add node-sass
583 | ```
584 |
585 | Now you can rename `src/App.css` to `src/App.scss` and update `src/App.js` to import `src/App.scss`.
586 | This file and any other file will be automatically compiled if imported with the extension `.scss` or `.sass`.
587 |
588 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions.
589 |
590 | This will allow you to do imports like
591 |
592 | ```scss
593 | @import 'styles/_colors.scss'; // assuming a styles directory under src/
594 | @import '~nprogress/nprogress'; // importing a css file from the nprogress node module
595 | ```
596 |
597 | > **Tip:** You can opt into using this feature with [CSS modules](#adding-a-css-modules-stylesheet) too!
598 |
599 | > **Note:** You must prefix imports from `node_modules` with `~` as displayed above.
600 |
601 | > **Note:** If you're using Flow, add the following to your `.flowconfig` so it'll recognize the `.sass` or `.scss` imports.
602 |
603 | ```
604 | [options]
605 | module.file_ext=.sass
606 | module.file_ext=.scss
607 | ```
608 |
609 | ## Post-Processing CSS
610 |
611 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it.
612 |
613 | Support for new CSS features like the [`all` property](https://developer.mozilla.org/en-US/docs/Web/CSS/all), [`break` properties](https://www.w3.org/TR/css-break-3/#breaking-controls), [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables), and [media query ranges](https://www.w3.org/TR/mediaqueries-4/#range-context) are automatically polyfilled to add support for older browsers.
614 |
615 | You can customize your target support browsers by adjusting the `browserslist` key in `package.json` according to the [Browserslist specification](https://github.com/browserslist/browserslist#readme).
616 |
617 | For example, this:
618 |
619 | ```css
620 | .App {
621 | display: flex;
622 | flex-direction: row;
623 | align-items: center;
624 | }
625 | ```
626 |
627 | becomes this:
628 |
629 | ```css
630 | .App {
631 | display: -webkit-box;
632 | display: -ms-flexbox;
633 | display: flex;
634 | -webkit-box-orient: horizontal;
635 | -webkit-box-direction: normal;
636 | -ms-flex-direction: row;
637 | flex-direction: row;
638 | -webkit-box-align: center;
639 | -ms-flex-align: center;
640 | align-items: center;
641 | }
642 | ```
643 |
644 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
645 |
646 | [CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) prefixing is disabled by default, but it will **not** strip manual prefixing.
647 | If you'd like to opt-in to CSS Grid prefixing, [first familiarize yourself about its limitations](https://github.com/postcss/autoprefixer#does-autoprefixer-polyfill-grid-layout-for-ie).
648 | To enable CSS Grid prefixing, add `/* autoprefixer grid: on */` to the top of your CSS file.
649 |
650 | ## Adding Images, Fonts, and Files
651 |
652 | With Webpack, using static assets like images and fonts works similarly to CSS.
653 |
654 | You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF.
655 |
656 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebook/create-react-app/issues/1153).
657 |
658 | Here is an example:
659 |
660 | ```js
661 | import React from 'react';
662 | import logo from './logo.png'; // Tell Webpack this JS file uses this image
663 |
664 | console.log(logo); // /logo.84287d09.png
665 |
666 | function Header() {
667 | // Import result is the URL of your image
668 | return ;
669 | }
670 |
671 | export default Header;
672 | ```
673 |
674 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths.
675 |
676 | This works in CSS too:
677 |
678 | ```css
679 | .Logo {
680 | background-image: url(./logo.png);
681 | }
682 | ```
683 |
684 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets.
685 |
686 | Please be advised that this is also a custom feature of Webpack.
687 |
688 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).
689 | An alternative way of handling static assets is described in the next section.
690 |
691 | ### Adding SVGs
692 |
693 | > Note: this feature is available with `react-scripts@2.0.0` and higher.
694 |
695 | One way to add SVG files was described in the section above. You can also import SVGs directly as React components. You can use either of the two approaches. In your code it would look like this:
696 |
697 | ```js
698 | import { ReactComponent as Logo } from './logo.svg';
699 | const App = () => (
700 |
701 | {/* Logo is an actual React component */}
702 |
703 |
704 | );
705 | ```
706 |
707 | This is handy if you don't want to load SVG as a separate file. Don't forget the curly braces in the import! The `ReactComponent` import name is special and tells Create React App that you want a React component that renders an SVG, rather than its filename.
708 |
709 | ## Using the `public` Folder
710 |
711 | > Note: this feature is available with `react-scripts@0.5.0` and higher.
712 |
713 | ### Changing the HTML
714 |
715 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title).
716 | The `
1301 | ```
1302 |
1303 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.**
1304 |
1305 | ## Running Tests
1306 |
1307 | > Note: this feature is available with `react-scripts@0.3.0` and higher.
1308 |
1309 | > [Read the migration guide to learn how to enable it in older projects!](https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
1310 |
1311 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try.
1312 |
1313 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness.
1314 |
1315 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks.
1316 |
1317 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App.
1318 |
1319 | ### Filename Conventions
1320 |
1321 | Jest will look for test files with any of the following popular naming conventions:
1322 |
1323 | - Files with `.js` suffix in `__tests__` folders.
1324 | - Files with `.test.js` suffix.
1325 | - Files with `.spec.js` suffix.
1326 |
1327 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder.
1328 |
1329 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects.
1330 |
1331 | ### Command Line Interface
1332 |
1333 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code.
1334 |
1335 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run:
1336 |
1337 | 
1338 |
1339 | ### Version Control Integration
1340 |
1341 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests.
1342 |
1343 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests.
1344 |
1345 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository.
1346 |
1347 | ### Writing Tests
1348 |
1349 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended.
1350 |
1351 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
1352 |
1353 | ```js
1354 | import sum from './sum';
1355 |
1356 | it('sums numbers', () => {
1357 | expect(sum(1, 2)).toEqual(3);
1358 | expect(sum(2, 2)).toEqual(4);
1359 | });
1360 | ```
1361 |
1362 | All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
1363 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies” or mock functions.
1364 |
1365 | ### Testing Components
1366 |
1367 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes.
1368 |
1369 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components:
1370 |
1371 | ```js
1372 | import React from 'react';
1373 | import ReactDOM from 'react-dom';
1374 | import App from './App';
1375 |
1376 | it('renders without crashing', () => {
1377 | const div = document.createElement('div');
1378 | ReactDOM.render( , div);
1379 | });
1380 | ```
1381 |
1382 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`.
1383 |
1384 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior.
1385 |
1386 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run:
1387 |
1388 | ```sh
1389 | npm install --save enzyme enzyme-adapter-react-16 react-test-renderer
1390 | ```
1391 |
1392 | Alternatively you may use `yarn`:
1393 |
1394 | ```sh
1395 | yarn add enzyme enzyme-adapter-react-16 react-test-renderer
1396 | ```
1397 |
1398 | As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.)
1399 |
1400 | The adapter will also need to be configured in your [global setup file](#initializing-test-environment):
1401 |
1402 | #### `src/setupTests.js`
1403 |
1404 | ```js
1405 | import { configure } from 'enzyme';
1406 | import Adapter from 'enzyme-adapter-react-16';
1407 |
1408 | configure({ adapter: new Adapter() });
1409 | ```
1410 |
1411 | > Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting.
1412 |
1413 | Now you can write a smoke test with it:
1414 |
1415 | ```js
1416 | import React from 'react';
1417 | import { shallow } from 'enzyme';
1418 | import App from './App';
1419 |
1420 | it('renders without crashing', () => {
1421 | shallow( );
1422 | });
1423 | ```
1424 |
1425 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `` 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.
1426 |
1427 | 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.
1428 |
1429 | Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
1430 |
1431 | ```js
1432 | import React from 'react';
1433 | import { shallow } from 'enzyme';
1434 | import App from './App';
1435 |
1436 | it('renders welcome message', () => {
1437 | const wrapper = shallow( );
1438 | const welcome = Welcome to React ;
1439 | // expect(wrapper.contains(welcome)).toBe(true);
1440 | expect(wrapper.contains(welcome)).toEqual(true);
1441 | });
1442 | ```
1443 |
1444 | All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/en/expect.html).
1445 | Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below.
1446 |
1447 | Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written more simply with jest-enzyme.
1448 |
1449 | ```js
1450 | expect(wrapper).toContainReact(welcome);
1451 | ```
1452 |
1453 | To enable this, install `jest-enzyme`:
1454 |
1455 | ```sh
1456 | npm install --save jest-enzyme
1457 | ```
1458 |
1459 | Alternatively you may use `yarn`:
1460 |
1461 | ```sh
1462 | yarn add jest-enzyme
1463 | ```
1464 |
1465 | Import it in [`src/setupTests.js`](#initializing-test-environment) to make its matchers available in every test:
1466 |
1467 | ```js
1468 | import 'jest-enzyme';
1469 | ```
1470 |
1471 | #### Use `react-testing-library`
1472 |
1473 | As an alternative or companion to `enzyme`, you may consider using `react-testing-library`. [`react-testing-library`](https://github.com/kentcdodds/react-testing-library) is a library for testing React components in a way that resembles the way the components are used by end users. It is well suited for unit, integration, and end-to-end testing of React components and applications. It works more directly with DOM nodes, and therefore it's recommended to use with [`jest-dom`](https://github.com/gnapse/jest-dom) for improved assertions.
1474 |
1475 | To install `react-testing-library` and `jest-dom`, you can run:
1476 |
1477 | ```sh
1478 | npm install --save react-testing-library jest-dom
1479 | ```
1480 |
1481 | Alternatively you may use `yarn`:
1482 |
1483 | ```sh
1484 | yarn add react-testing-library jest-dom
1485 | ```
1486 |
1487 | Similar to `enzyme` you can create a `src/setupTests.js` file to avoid boilerplate in your test files:
1488 |
1489 | ```js
1490 | // react-testing-library renders your components to document.body,
1491 | // this will ensure they're removed after each test.
1492 | import 'react-testing-library/cleanup-after-each';
1493 |
1494 | // this adds jest-dom's custom assertions
1495 | import 'jest-dom/extend-expect';
1496 | ```
1497 |
1498 | Here's an example of using `react-testing-library` and `jest-dom` for testing that the ` ` component renders "Welcome to React".
1499 |
1500 | ```js
1501 | import React from 'react';
1502 | import { render } from 'react-testing-library';
1503 | import App from './App';
1504 |
1505 | it('renders welcome message', () => {
1506 | const { getByText } = render( );
1507 | expect(getByText('Welcome to React')).toBeInTheDocument();
1508 | });
1509 | ```
1510 |
1511 | Learn more about the utilities provided by `react-testing-library` to facilitate testing asynchronous interactions as well as selecting form elements from [the `react-testing-library` documentation](https://github.com/kentcdodds/react-testing-library) and [examples](https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples).
1512 |
1513 | ### Using Third Party Assertion Libraries
1514 |
1515 | 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).
1516 |
1517 | 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:
1518 |
1519 | ```js
1520 | import sinon from 'sinon';
1521 | import { expect } from 'chai';
1522 | ```
1523 |
1524 | and then use them in your tests like you normally do.
1525 |
1526 | ### Initializing Test Environment
1527 |
1528 | > Note: this feature is available with `react-scripts@0.4.0` and higher.
1529 |
1530 | 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.
1531 |
1532 | For example:
1533 |
1534 | #### `src/setupTests.js`
1535 |
1536 | ```js
1537 | const localStorageMock = {
1538 | getItem: jest.fn(),
1539 | setItem: jest.fn(),
1540 | clear: jest.fn(),
1541 | };
1542 | global.localStorage = localStorageMock;
1543 | ```
1544 |
1545 | > Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it, so you should manually create the property `setupTestFrameworkScriptFile` in the configuration for Jest, something like the following:
1546 |
1547 | > ```js
1548 | > "jest": {
1549 | > // ...
1550 | > "setupTestFrameworkScriptFile": "/src/setupTests.js"
1551 | > }
1552 | > ```
1553 |
1554 | ### Focusing and Excluding Tests
1555 |
1556 | You can replace `it()` with `xit()` to temporarily exclude a test from being executed.
1557 | Similarly, `fit()` lets you focus on a specific test without running any other tests.
1558 |
1559 | ### Coverage Reporting
1560 |
1561 | Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.
1562 | Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this:
1563 |
1564 | 
1565 |
1566 | Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow.
1567 |
1568 | #### Configuration
1569 |
1570 | The default Jest coverage configuration can be overridden by adding any of the following supported keys to a Jest config in your package.json.
1571 |
1572 | Supported overrides:
1573 |
1574 | - [`collectCoverageFrom`](https://facebook.github.io/jest/docs/en/configuration.html#collectcoveragefrom-array)
1575 | - [`coverageReporters`](https://facebook.github.io/jest/docs/en/configuration.html#coveragereporters-array-string)
1576 | - [`coverageThreshold`](https://facebook.github.io/jest/docs/en/configuration.html#coveragethreshold-object)
1577 | - [`snapshotSerializers`](https://facebook.github.io/jest/docs/en/configuration.html#snapshotserializers-array-string)
1578 |
1579 | Example package.json:
1580 |
1581 | ```json
1582 | {
1583 | "name": "your-package",
1584 | "jest": {
1585 | "collectCoverageFrom": [
1586 | "src/**/*.{js,jsx}",
1587 | "!/node_modules/",
1588 | "!/path/to/dir/"
1589 | ],
1590 | "coverageThreshold": {
1591 | "global": {
1592 | "branches": 90,
1593 | "functions": 90,
1594 | "lines": 90,
1595 | "statements": 90
1596 | }
1597 | },
1598 | "coverageReporters": ["text"],
1599 | "snapshotSerializers": ["my-serializer-module"]
1600 | }
1601 | }
1602 | ```
1603 |
1604 | ### Continuous Integration
1605 |
1606 | 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`.
1607 |
1608 | 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.
1609 |
1610 | Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
1611 |
1612 | ### On CI servers
1613 |
1614 | #### Travis CI
1615 |
1616 | 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.
1617 | 1. Add a `.travis.yml` file to your git repository.
1618 |
1619 | ```
1620 | language: node_js
1621 | node_js:
1622 | - 8
1623 | cache:
1624 | directories:
1625 | - node_modules
1626 | script:
1627 | - npm run build
1628 | - npm test
1629 | ```
1630 |
1631 | 1. Trigger your first build with a git push.
1632 | 1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
1633 |
1634 | #### CircleCI
1635 |
1636 | Follow [this article](https://medium.com/@knowbody/circleci-and-zeits-now-sh-c9b7eebcd3c1) to set up CircleCI with a Create React App project.
1637 |
1638 | ### On your own environment
1639 |
1640 | ##### Windows (cmd.exe)
1641 |
1642 | ```cmd
1643 | set CI=true&&npm test
1644 | ```
1645 |
1646 | ```cmd
1647 | set CI=true&&npm run build
1648 | ```
1649 |
1650 | (Note: the lack of whitespace is intentional.)
1651 |
1652 | ##### Windows (Powershell)
1653 |
1654 | ```Powershell
1655 | ($env:CI = $true) -and (npm test)
1656 | ```
1657 |
1658 | ```Powershell
1659 | ($env:CI = $true) -and (npm run build)
1660 | ```
1661 |
1662 | ##### Linux, macOS (Bash)
1663 |
1664 | ```bash
1665 | CI=true npm test
1666 | ```
1667 |
1668 | ```bash
1669 | CI=true npm run build
1670 | ```
1671 |
1672 | The test command will force Jest to run tests once instead of launching the watcher.
1673 |
1674 | > If you find yourself doing this often in development, please [file an issue](https://github.com/facebook/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.
1675 |
1676 | The build command will check for linter warnings and fail if any are found.
1677 |
1678 | ### Disabling jsdom
1679 |
1680 | If you know that none of your tests depend on [jsdom](https://github.com/tmpvar/jsdom), you can safely set `--env=node`, and your tests will run faster:
1681 |
1682 | ```diff
1683 | "scripts": {
1684 | "start": "react-scripts start",
1685 | "build": "react-scripts build",
1686 | - "test": "react-scripts test"
1687 | + "test": "react-scripts test --env=node"
1688 | ```
1689 |
1690 | To help you make up your mind, here is a list of APIs that **need jsdom**:
1691 |
1692 | - Any browser globals like `window` and `document`
1693 | - [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render)
1694 | - [`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)
1695 | - [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1696 |
1697 | In contrast, **jsdom is not needed** for the following APIs:
1698 |
1699 | - [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering)
1700 | - [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
1701 |
1702 | Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html).
1703 |
1704 | ### Snapshot Testing
1705 |
1706 | 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)
1707 |
1708 | ### Editor Integration
1709 |
1710 | 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.
1711 |
1712 | 
1713 |
1714 | ## Debugging Tests
1715 |
1716 | There are various ways to setup a debugger for your Jest tests. We cover debugging in Chrome and [Visual Studio Code](https://code.visualstudio.com/).
1717 |
1718 | > Note: debugging tests requires Node 8 or higher.
1719 |
1720 | ### Debugging Tests in Chrome
1721 |
1722 | Add the following to the `scripts` section in your project's `package.json`
1723 |
1724 | ```json
1725 | "scripts": {
1726 | "test:debug": "react-scripts --inspect-brk test --runInBand"
1727 | }
1728 | ```
1729 |
1730 | Place `debugger;` statements in any test and run:
1731 |
1732 | ```bash
1733 | $ npm run test:debug
1734 | ```
1735 |
1736 | This will start running your Jest tests, but pause before executing to allow a debugger to attach to the process.
1737 |
1738 | Open the following in Chrome
1739 |
1740 | ```
1741 | about:inspect
1742 | ```
1743 |
1744 | After opening that link, the Chrome Developer Tools will be displayed. Select `inspect` on your process and a breakpoint will be set at the first line of the react script (this is done simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.
1745 |
1746 | > Note: the --runInBand cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.
1747 |
1748 | ### Debugging Tests in Visual Studio Code
1749 |
1750 | Debugging Jest tests is supported out of the box for [Visual Studio Code](https://code.visualstudio.com).
1751 |
1752 | Use the following [`launch.json`](https://code.visualstudio.com/docs/editor/debugging#_launch-configurations) configuration file:
1753 |
1754 | ```
1755 | {
1756 | "version": "0.2.0",
1757 | "configurations": [
1758 | {
1759 | "name": "Debug CRA Tests",
1760 | "type": "node",
1761 | "request": "launch",
1762 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts",
1763 | "args": [
1764 | "test",
1765 | "--runInBand",
1766 | "--no-cache"
1767 | ],
1768 | "cwd": "${workspaceRoot}",
1769 | "protocol": "inspector",
1770 | "console": "integratedTerminal",
1771 | "internalConsoleOptions": "neverOpen"
1772 | }
1773 | ]
1774 | }
1775 | ```
1776 |
1777 | ## Developing Components in Isolation
1778 |
1779 | Usually, in an app, you have a lot of UI components, and each of them has many different states.
1780 | For an example, a simple button component could have following states:
1781 |
1782 | - In a regular state, with a text label.
1783 | - In the disabled mode.
1784 | - In a loading state.
1785 |
1786 | Usually, it’s hard to see these states without running a sample app or some examples.
1787 |
1788 | Create React App doesn’t include any tools for this by default, but you can easily add [Storybook for React](https://storybook.js.org) ([source](https://github.com/storybooks/storybook)) or [React Styleguidist](https://react-styleguidist.js.org/) ([source](https://github.com/styleguidist/react-styleguidist)) to your project. **These are third-party tools that let you develop components and see all their states in isolation from your app**.
1789 |
1790 | 
1791 |
1792 | You can also deploy your Storybook or style guide 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.
1793 |
1794 | ### Getting Started with Storybook
1795 |
1796 | Storybook is a development environment for React UI components. It allows you to browse a component library, view the different states of each component, and interactively develop and test components.
1797 |
1798 | First, install the following npm package globally:
1799 |
1800 | ```sh
1801 | npm install -g @storybook/cli
1802 | ```
1803 |
1804 | Then, run the following command inside your app’s directory:
1805 |
1806 | ```sh
1807 | getstorybook
1808 | ```
1809 |
1810 | After that, follow the instructions on the screen.
1811 |
1812 | Learn more about React Storybook:
1813 |
1814 | - [Learn Storybook (tutorial)](https://learnstorybook.com)
1815 | - [Documentation](https://storybook.js.org/basics/introduction/)
1816 | - [GitHub Repo](https://github.com/storybooks/storybook)
1817 | - [Snapshot Testing UI](https://github.com/storybooks/storybook/tree/master/addons/storyshots) with Storybook + addon/storyshot
1818 |
1819 | ### Getting Started with Styleguidist
1820 |
1821 | Styleguidist combines a style guide, where all your components are presented on a single page with their props documentation and usage examples, with an environment for developing components in isolation, similar to Storybook. In Styleguidist you write examples in Markdown, where each code snippet is rendered as a live editable playground.
1822 |
1823 | First, install Styleguidist:
1824 |
1825 | ```sh
1826 | npm install --save react-styleguidist
1827 | ```
1828 |
1829 | Alternatively you may use `yarn`:
1830 |
1831 | ```sh
1832 | yarn add react-styleguidist
1833 | ```
1834 |
1835 | Then, add these scripts to your `package.json`:
1836 |
1837 | ```diff
1838 | "scripts": {
1839 | + "styleguide": "styleguidist server",
1840 | + "styleguide:build": "styleguidist build",
1841 | "start": "react-scripts start",
1842 | ```
1843 |
1844 | Then, run the following command inside your app’s directory:
1845 |
1846 | ```sh
1847 | npm run styleguide
1848 | ```
1849 |
1850 | After that, follow the instructions on the screen.
1851 |
1852 | Learn more about React Styleguidist:
1853 |
1854 | - [GitHub Repo](https://github.com/styleguidist/react-styleguidist)
1855 | - [Documentation](https://react-styleguidist.js.org/docs/getting-started.html)
1856 |
1857 | ## Publishing Components to npm
1858 |
1859 | Create React App doesn't provide any built-in functionality to publish a component to npm. If you're ready to extract a component from your project so other people can use it, we recommend moving it to a separate directory outside of your project and then using a tool like [nwb](https://github.com/insin/nwb#react-components-and-libraries) to prepare it for publishing.
1860 |
1861 | ## Making a Progressive Web App
1862 |
1863 | The production build has all the tools necessary to generate a first-class
1864 | [Progressive Web App](https://developers.google.com/web/progressive-web-apps/),
1865 | but **the offline/cache-first behavior is opt-in only**. By default,
1866 | the build process will generate a service worker file, but it will not be
1867 | registered, so it will not take control of your production web app.
1868 |
1869 | In order to opt-in to the offline-first behavior, developers should look for the
1870 | following in their [`src/index.js`](src/index.js) file:
1871 |
1872 | ```js
1873 | // If you want your app to work offline and load faster, you can change
1874 | // unregister() to register() below. Note this comes with some pitfalls.
1875 | // Learn more about service workers: http://bit.ly/CRA-PWA
1876 | serviceWorker.unregister();
1877 | ```
1878 |
1879 | As the comment states, switching `serviceWorker.unregister()` to
1880 | `serviceWorker.register()` will opt you in to using the service worker.
1881 |
1882 | ### Why Opt-in?
1883 |
1884 | Offline-first Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience:
1885 |
1886 | - All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background.
1887 | - Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the subway.
1888 | - On mobile devices, your app can be added directly to the user's home screen, app icon and all. This eliminates the need for the app store.
1889 |
1890 | However, they [can make debugging deployments more challenging](https://github.com/facebook/create-react-app/issues/2398) so, starting with Create React App 2, service workers are opt-in.
1891 |
1892 | The [`workbox-webpack-plugin`](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin)
1893 | is integrated into production configuration,
1894 | and it will take care of generating a service worker file that will automatically
1895 | precache all of your local assets and keep them up to date as you deploy updates.
1896 | The service worker will use a [cache-first strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network)
1897 | for handling all requests for local assets, including
1898 | [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)
1899 | for your HTML, ensuring that your web app is consistently fast, even on a slow
1900 | or unreliable network.
1901 |
1902 | ### Offline-First Considerations
1903 |
1904 | If you do decide to opt-in to service worker registration, please take the
1905 | following into account:
1906 |
1907 | 1. After the initial caching is done, the [service worker lifecycle](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle)
1908 | controls when updated content ends up being shown to users. In order to guard against
1909 | [race conditions with lazy-loaded content](https://github.com/facebook/create-react-app/issues/3613#issuecomment-353467430),
1910 | the default behavior is to conservatively keep the updated service worker in the "[waiting](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting)"
1911 | state. This means that users will end up seeing older content until they close (reloading is not
1912 | enough) their existing, open tabs. See [this blog post](https://jeffy.info/2018/10/10/sw-in-c-r-a.html)
1913 | for more details about this behavior.
1914 |
1915 | 1. Users aren't always familiar with offline-first web apps. It can be useful to
1916 | [let the user know](https://developers.google.com/web/fundamentals/instant-and-offline/offline-ux#inform_the_user_when_the_app_is_ready_for_offline_consumption)
1917 | when the service worker has finished populating your caches (showing a "This web
1918 | app works offline!" message) and also let them know when the service worker has
1919 | fetched the latest updates that will be available the next time they load the
1920 | page (showing a "New content is available once existing tabs are closed." message). Showing
1921 | this messages is currently left as an exercise to the developer, but as a
1922 | starting point, you can make use of the logic included in [`src/serviceWorker.js`](src/serviceWorker.js), which
1923 | demonstrates which service worker lifecycle events to listen for to detect each
1924 | scenario, and which as a default, just logs appropriate messages to the
1925 | JavaScript console.
1926 |
1927 | 1. Service workers [require HTTPS](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers#you_need_https),
1928 | although to facilitate local testing, that policy
1929 | [does not apply to `localhost`](http://stackoverflow.com/questions/34160509/options-for-testing-service-workers-via-http/34161385#34161385).
1930 | If your production web server does not support HTTPS, then the service worker
1931 | registration will fail, but the rest of your web app will remain functional.
1932 |
1933 | 1. The service worker is only enabled in the [production environment](#deployment),
1934 | e.g. the output of `npm run build`. It's recommended that you do not enable an
1935 | offline-first service worker in a development environment, as it can lead to
1936 | frustration when previously cached assets are used and do not include the latest
1937 | changes you've made locally.
1938 |
1939 | 1. If you _need_ to test your offline-first service worker locally, build
1940 | the application (using `npm run build`) and run a simple http server from your
1941 | build directory. After running the build script, `create-react-app` will give
1942 | instructions for one way to test your production build locally and the [deployment instructions](#deployment) have
1943 | instructions for using other methods. _Be sure to always use an
1944 | incognito window to avoid complications with your browser cache._
1945 |
1946 | 1. By default, the generated service worker file will not intercept or cache any
1947 | cross-origin traffic, like HTTP [API requests](#integrating-with-an-api-backend),
1948 | images, or embeds loaded from a different domain.
1949 |
1950 | ### Progressive Web App Metadata
1951 |
1952 | The default configuration includes a web app manifest located at
1953 | [`public/manifest.json`](public/manifest.json), that you can customize with
1954 | details specific to your web application.
1955 |
1956 | When a user adds a web app to their homescreen using Chrome or Firefox on
1957 | Android, the metadata in [`manifest.json`](public/manifest.json) determines what
1958 | icons, names, and branding colors to use when the web app is displayed.
1959 | [The Web App Manifest guide](https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/)
1960 | provides more context about what each field means, and how your customizations
1961 | will affect your users' experience.
1962 |
1963 | Progressive web apps that have been added to the homescreen will load faster and
1964 | work offline when there's an active service worker. That being said, the
1965 | metadata from the web app manifest will still be used regardless of whether or
1966 | not you opt-in to service worker registration.
1967 |
1968 | ## Analyzing the Bundle Size
1969 |
1970 | [Source map explorer](https://www.npmjs.com/package/source-map-explorer) analyzes
1971 | JavaScript bundles using the source maps. This helps you understand where code
1972 | bloat is coming from.
1973 |
1974 | To add Source map explorer to a Create React App project, follow these steps:
1975 |
1976 | ```sh
1977 | npm install --save source-map-explorer
1978 | ```
1979 |
1980 | Alternatively you may use `yarn`:
1981 |
1982 | ```sh
1983 | yarn add source-map-explorer
1984 | ```
1985 |
1986 | Then in `package.json`, add the following line to `scripts`:
1987 |
1988 | ```diff
1989 | "scripts": {
1990 | + "analyze": "source-map-explorer build/static/js/main.*",
1991 | "start": "react-scripts start",
1992 | "build": "react-scripts build",
1993 | "test": "react-scripts test",
1994 | ```
1995 |
1996 | Then to analyze the bundle run the production build then run the analyze
1997 | script.
1998 |
1999 | ```
2000 | npm run build
2001 | npm run analyze
2002 | ```
2003 |
2004 | ## Deployment
2005 |
2006 | `npm run build` creates a `build` directory with a production build of your app. Set up your favorite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main..js` are served with the contents of the `/static/js/main..js` file.
2007 |
2008 | ### Static Server
2009 |
2010 | For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest:
2011 |
2012 | ```sh
2013 | npm install -g serve
2014 | serve -s build
2015 | ```
2016 |
2017 | The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-p` or `--port` flags.
2018 |
2019 | Run this command to get a full list of the options available:
2020 |
2021 | ```sh
2022 | serve -h
2023 | ```
2024 |
2025 | ### Other Solutions
2026 |
2027 | You don’t necessarily need a static server in order to run a Create React App project in production. It works just as fine integrated into an existing dynamic one.
2028 |
2029 | Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
2030 |
2031 | ```javascript
2032 | const express = require('express');
2033 | const path = require('path');
2034 | const app = express();
2035 |
2036 | app.use(express.static(path.join(__dirname, 'build')));
2037 |
2038 | app.get('/', function(req, res) {
2039 | res.sendFile(path.join(__dirname, 'build', 'index.html'));
2040 | });
2041 |
2042 | app.listen(9000);
2043 | ```
2044 |
2045 | The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node.
2046 |
2047 | The `build` folder with static assets is the only output produced by Create React App.
2048 |
2049 | 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.
2050 |
2051 | ### Serving Apps with Client-Side Routing
2052 |
2053 | 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.
2054 |
2055 | 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:
2056 |
2057 | ```diff
2058 | app.use(express.static(path.join(__dirname, 'build')));
2059 |
2060 | -app.get('/', function (req, res) {
2061 | +app.get('/*', function (req, res) {
2062 | res.sendFile(path.join(__dirname, 'build', 'index.html'));
2063 | });
2064 | ```
2065 |
2066 | If you’re using [Apache HTTP Server](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this:
2067 |
2068 | ```
2069 | Options -MultiViews
2070 | RewriteEngine On
2071 | RewriteCond %{REQUEST_FILENAME} !-f
2072 | RewriteRule ^ index.html [QSA,L]
2073 | ```
2074 |
2075 | It will get copied to the `build` folder when you run `npm run build`.
2076 |
2077 | If you’re using [Apache Tomcat](http://tomcat.apache.org/), you need to follow [this Stack Overflow answer](https://stackoverflow.com/a/41249464/4878474).
2078 |
2079 | Now requests to `/todos/42` will be handled correctly both in development and in production.
2080 |
2081 | On a production build, and when you've [opted-in](#why-opt-in),
2082 | a [service worker](https://developers.google.com/web/fundamentals/primers/service-workers/) will automatically handle all navigation requests, like for
2083 | `/todos/42`, by serving the cached copy of your `index.html`. This
2084 | service worker navigation routing can be configured or disabled by
2085 | [`eject`ing](#npm-run-eject) and then modifying the
2086 | [`navigateFallback`](https://github.com/GoogleChrome/sw-precache#navigatefallback-string)
2087 | and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp)
2088 | options of the `SWPreachePlugin` [configuration](../config/webpack.config.prod.js).
2089 |
2090 | When users install your app to the homescreen of their device the default configuration will make a shortcut to `/index.html`. This may not work for client-side routers which expect the app to be served from `/`. Edit the web app manifest at [`public/manifest.json`](public/manifest.json) and change `start_url` to match the required URL scheme, for example:
2091 |
2092 | ```js
2093 | "start_url": ".",
2094 | ```
2095 |
2096 | ### Building for Relative Paths
2097 |
2098 | By default, Create React App produces a build assuming your app is hosted at the server root.
2099 | To override this, specify the `homepage` in your `package.json`, for example:
2100 |
2101 | ```js
2102 | "homepage": "http://mywebsite.com/relativepath",
2103 | ```
2104 |
2105 | This will let Create React App correctly infer the root path to use in the generated HTML file.
2106 |
2107 | **Note**: If you are using `react-router@^4`, you can root ` `s using the `basename` prop on any ``.
2108 | More information [here](https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string).
2109 |
2110 | For example:
2111 |
2112 | ```js
2113 |
2114 | // renders
2115 | ```
2116 |
2117 | #### Serving the Same Build from Different Paths
2118 |
2119 | > Note: this feature is available with `react-scripts@0.9.0` and higher.
2120 |
2121 | 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`:
2122 |
2123 | ```js
2124 | "homepage": ".",
2125 | ```
2126 |
2127 | 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.
2128 |
2129 | ### Customizing Environment Variables for Arbitrary Build Environments
2130 |
2131 | You can create an arbitrary build environment by creating a custom `.env` file and loading it using [env-cmd](https://www.npmjs.com/package/env-cmd).
2132 |
2133 | For example, to create a build environment for a staging environment:
2134 |
2135 | 1. Create a file called `.env.staging`
2136 | 1. Set environment variables as you would any other `.env` file (e.g. `REACT_APP_API_URL=http://api-staging.example.com`)
2137 | 1. Install [env-cmd](https://www.npmjs.com/package/env-cmd)
2138 | ```sh
2139 | $ npm install env-cmd --save
2140 | $ # or
2141 | $ yarn add env-cmd
2142 | ```
2143 | 1. Add a new script to your `package.json`, building with your new environment:
2144 | ```json
2145 | {
2146 | "scripts": {
2147 | "build:staging": "env-cmd .env.staging npm run build"
2148 | }
2149 | }
2150 | ```
2151 |
2152 | Now you can run `npm run build:staging` to build with the staging environment config.
2153 | You can specify other environments in the same way.
2154 |
2155 | Variables in `.env.production` will be used as fallback because `NODE_ENV` will always be set to `production` for a build.
2156 |
2157 | ### [Azure](https://azure.microsoft.com/)
2158 |
2159 | See [this](https://medium.com/@to_pe/deploying-create-react-app-on-microsoft-azure-c0f6686a4321) blog post on how to deploy your React app to Microsoft Azure.
2160 |
2161 | See [this](https://medium.com/@strid/host-create-react-app-on-azure-986bc40d5bf2#.pycfnafbg) blog post or [this](https://github.com/ulrikaugustsson/azure-appservice-static) repo for a way to use automatic deployment to Azure App Service.
2162 |
2163 | ### [Firebase](https://firebase.google.com/)
2164 |
2165 | 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.
2166 |
2167 | 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`.
2168 |
2169 | ```sh
2170 | === Project Setup
2171 |
2172 | First, let's associate this project directory with a Firebase project.
2173 | You can create multiple project aliases by running firebase use --add,
2174 | but for now we'll just set up a default project.
2175 |
2176 | ? What Firebase project do you want to associate as default? Example app (example-app-fd690)
2177 |
2178 | === Database Setup
2179 |
2180 | Firebase Realtime Database Rules allow you to define how your data should be
2181 | structured and when your data can be read from and written to.
2182 |
2183 | ? What file should be used for Database Rules? database.rules.json
2184 | ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json.
2185 | Future modifications to database.rules.json will update Database Rules when you run
2186 | firebase deploy.
2187 |
2188 | === Hosting Setup
2189 |
2190 | Your public directory is the folder (relative to your project directory) that
2191 | will contain Hosting assets to uploaded with firebase deploy. If you
2192 | have a build process for your assets, use your build's output directory.
2193 |
2194 | ? What do you want to use as your public directory? build
2195 | ? Configure as a single-page app (rewrite all urls to /index.html)? Yes
2196 | ✔ Wrote build/index.html
2197 |
2198 | i Writing configuration info to firebase.json...
2199 | i Writing project information to .firebaserc...
2200 |
2201 | ✔ Firebase initialization complete!
2202 | ```
2203 |
2204 | IMPORTANT: you need to set proper HTTP caching headers for `service-worker.js` file in `firebase.json` file or you will not be able to see changes after first deployment ([issue #2440](https://github.com/facebook/create-react-app/issues/2440)). It should be added inside `"hosting"` key like next:
2205 |
2206 | ```
2207 | {
2208 | "hosting": {
2209 | ...
2210 | "headers": [
2211 | {"source": "/service-worker.js", "headers": [{"key": "Cache-Control", "value": "no-cache"}]}
2212 | ]
2213 | ...
2214 | ```
2215 |
2216 | Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`.
2217 |
2218 | ```sh
2219 | === Deploying to 'example-app-fd690'...
2220 |
2221 | i deploying database, hosting
2222 | ✔ database: rules ready to deploy.
2223 | i hosting: preparing build directory for upload...
2224 | Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully
2225 | ✔ hosting: 8 files uploaded successfully
2226 | i starting release process (may take several minutes)...
2227 |
2228 | ✔ Deploy complete!
2229 |
2230 | Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
2231 | Hosting URL: https://example-app-fd690.firebaseapp.com
2232 | ```
2233 |
2234 | For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup).
2235 |
2236 | ### [GitHub Pages](https://pages.github.com/)
2237 |
2238 | > Note: this feature is available with `react-scripts@0.2.0` and higher.
2239 |
2240 | #### Step 1: Add `homepage` to `package.json`
2241 |
2242 | **The step below is important!**
2243 | **If you skip it, your app will not deploy correctly.**
2244 |
2245 | Open your `package.json` and add a `homepage` field for your project:
2246 |
2247 | ```json
2248 | "homepage": "https://myusername.github.io/my-app",
2249 | ```
2250 |
2251 | or for a GitHub user page:
2252 |
2253 | ```json
2254 | "homepage": "https://myusername.github.io",
2255 | ```
2256 |
2257 | or for a custom domain page:
2258 |
2259 | ```json
2260 | "homepage": "https://mywebsite.com",
2261 | ```
2262 |
2263 | Create React App uses the `homepage` field to determine the root URL in the built HTML file.
2264 |
2265 | #### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`
2266 |
2267 | Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
2268 |
2269 | To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run:
2270 |
2271 | ```sh
2272 | npm install --save gh-pages
2273 | ```
2274 |
2275 | Alternatively you may use `yarn`:
2276 |
2277 | ```sh
2278 | yarn add gh-pages
2279 | ```
2280 |
2281 | Add the following scripts in your `package.json`:
2282 |
2283 | ```diff
2284 | "scripts": {
2285 | + "predeploy": "npm run build",
2286 | + "deploy": "gh-pages -d build",
2287 | "start": "react-scripts start",
2288 | "build": "react-scripts build",
2289 | ```
2290 |
2291 | The `predeploy` script will run automatically before `deploy` is run.
2292 |
2293 | If you are deploying to a GitHub user page instead of a project page you'll need to make two
2294 | additional modifications:
2295 |
2296 | 1. First, change your repository's source branch to be any branch other than **master**.
2297 | 1. Additionally, tweak your `package.json` scripts to push deployments to **master**:
2298 |
2299 | ```diff
2300 | "scripts": {
2301 | "predeploy": "npm run build",
2302 | - "deploy": "gh-pages -d build",
2303 | + "deploy": "gh-pages -b master -d build",
2304 | ```
2305 |
2306 | #### Step 3: Deploy the site by running `npm run deploy`
2307 |
2308 | Then run:
2309 |
2310 | ```sh
2311 | npm run deploy
2312 | ```
2313 |
2314 | #### Step 4: Ensure your project’s settings use `gh-pages`
2315 |
2316 | Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch:
2317 |
2318 |
2319 |
2320 | #### Step 5: Optionally, configure the domain
2321 |
2322 | You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder.
2323 |
2324 | Your CNAME file should look like this:
2325 |
2326 | ```
2327 | mywebsite.com
2328 | ```
2329 |
2330 | #### Notes on client-side routing
2331 |
2332 | 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:
2333 |
2334 | - 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://reacttraining.com/react-router/web/api/Router) about different history implementations in React Router.
2335 | - 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).
2336 |
2337 | #### Troubleshooting
2338 |
2339 | ##### "/dev/tty: No such a device or address"
2340 |
2341 | If, when deploying, you get `/dev/tty: No such a device or address` or a similar error, try the following:
2342 |
2343 | 1. Create a new [Personal Access Token](https://github.com/settings/tokens)
2344 | 2. `git remote set-url origin https://:@github.com//` .
2345 | 3. Try `npm run deploy` again
2346 |
2347 | ##### "Cannot read property 'email' of null"
2348 |
2349 | If, when deploying, you get `Cannot read property 'email' of null`, try the following:
2350 |
2351 | 1. `git config --global user.name ''`
2352 | 2. `git config --global user.email ''`
2353 | 3. Try `npm run deploy` again
2354 |
2355 | ### [Heroku](https://www.heroku.com/)
2356 |
2357 | Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).
2358 | You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration).
2359 |
2360 | #### Resolving Heroku Deployment Errors
2361 |
2362 | Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases.
2363 |
2364 | ##### "Module not found: Error: Cannot resolve 'file' or 'directory'"
2365 |
2366 | If you get something like this:
2367 |
2368 | ```
2369 | remote: Failed to create a production build. Reason:
2370 | remote: Module not found: Error: Cannot resolve 'file' or 'directory'
2371 | MyDirectory in /tmp/build_1234/src
2372 | ```
2373 |
2374 | It 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.
2375 |
2376 | 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.
2377 |
2378 | ##### "Could not find a required file."
2379 |
2380 | If you exclude or ignore necessary files from the package you will see a error similar this one:
2381 |
2382 | ```
2383 | remote: Could not find a required file.
2384 | remote: Name: `index.html`
2385 | remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public
2386 | remote:
2387 | remote: npm ERR! Linux 3.13.0-105-generic
2388 | remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build"
2389 | ```
2390 |
2391 | In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local `.gitignore` or `~/.gitignore_global`.
2392 |
2393 | ### [Netlify](https://www.netlify.com/)
2394 |
2395 | **To do a manual deploy to Netlify’s CDN:**
2396 |
2397 | ```sh
2398 | npm install netlify-cli -g
2399 | netlify deploy
2400 | ```
2401 |
2402 | Choose `build` as the path to deploy.
2403 |
2404 | **To setup continuous delivery:**
2405 |
2406 | With this setup Netlify will build and deploy when you push to git or open a pull request:
2407 |
2408 | 1. [Start a new netlify project](https://app.netlify.com/signup)
2409 | 2. Pick your Git hosting service and select your repository
2410 | 3. Click `Build your site`
2411 |
2412 | **Support for client-side routing:**
2413 |
2414 | To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules:
2415 |
2416 | ```
2417 | /* /index.html 200
2418 | ```
2419 |
2420 | When you build the project, Create React App will place the `public` folder contents into the build output.
2421 |
2422 | ### [Now](https://zeit.co/now)
2423 |
2424 | Now offers a zero-configuration single-command deployment. You can use `now` to deploy your app for free.
2425 |
2426 | 1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
2427 |
2428 | 2. Build your app by running `npm run build`.
2429 |
2430 | 3. Move into the build directory by running `cd build`.
2431 |
2432 | 4. Run `now --name your-project-name` from within the build directory. You will see a **now.sh** URL in your output like this:
2433 |
2434 | ```
2435 | > Ready! https://your-project-name-tpspyhtdtk.now.sh (copied to clipboard)
2436 | ```
2437 |
2438 | Paste that URL into your browser when the build is complete, and you will see your deployed app.
2439 |
2440 | Details are available in [this article.](https://zeit.co/blog/unlimited-static)
2441 |
2442 | ### [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/)
2443 |
2444 | 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 and CloudFront.
2445 |
2446 | ### [Surge](https://surge.sh/)
2447 |
2448 | 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.
2449 |
2450 | When asked about the project path, make sure to specify the `build` folder, for example:
2451 |
2452 | ```sh
2453 | project path: /path/to/project/build
2454 | ```
2455 |
2456 | 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).
2457 |
2458 | ## Advanced Configuration
2459 |
2460 | You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).
2461 |
2462 | | Variable | Development | Production | Usage |
2463 | | :------------------: | :--------------------: | :----------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2464 | | 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. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to `npm start` will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the `.js` extension. |
2465 | | HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host. |
2466 | | 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. |
2467 | | HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode. |
2468 | | 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. |
2469 | | 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. |
2470 | | REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebook/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH]() environment variable points to your editor’s bin folder. You can also set it to `none` to disable it completely. |
2471 | | CHOKIDAR_USEPOLLING | :white_check_mark: | :x: | When set to `true`, the watcher runs in polling mode, as necessary inside a VM. Use this option if `npm start` isn't detecting changes. |
2472 | | GENERATE_SOURCEMAP | :x: | :white_check_mark: | When set to `false`, source maps are not generated for a production build. This solves OOM issues on some smaller machines. |
2473 | | NODE_PATH | :white_check_mark: | :white_check_mark: | Same as [`NODE_PATH` in Node.js](https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders), but only relative folders are allowed. Can be handy for emulating a monorepo setup by setting `NODE_PATH=src`. |
2474 | | INLINE_RUNTIME_CHUNK | :x: | :white_check_mark: | By default, Create React App will embed the runtime script into `index.html` during the production build. When set to `false`, the script will not be embedded and will be imported as usual. This is normally required when dealing with CSP. |
2475 |
2476 | ## Troubleshooting
2477 |
2478 | ### `npm start` doesn’t detect changes
2479 |
2480 | When you save a file while `npm start` is running, the browser should refresh with the updated code.
2481 | If this doesn’t happen, try one of the following workarounds:
2482 |
2483 | - If your project is in a Dropbox folder, try moving it out.
2484 | - 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/facebook/create-react-app/issues/1164) due to a Webpack bug.
2485 | - 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 [“Adjusting Your Text Editor”](https://webpack.js.org/guides/development/#adjusting-your-text-editor).
2486 | - 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).
2487 | - On Linux and macOS, you might need to [tweak system settings](https://github.com/webpack/docs/wiki/troubleshooting#not-enough-watchers) to allow more watchers.
2488 | - If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an `.env` file in your project directory if it doesn’t exist, and add `CHOKIDAR_USEPOLLING=true` to it. This ensures that the next time you run `npm start`, the watcher uses the polling mode, as necessary inside a VM.
2489 |
2490 | If none of these solutions help please leave a comment [in this thread](https://github.com/facebook/create-react-app/issues/659).
2491 |
2492 | ### `npm test` hangs or crashes on macOS Sierra
2493 |
2494 | If you run `npm test` and the console gets stuck after printing `react-scripts test` to the console there might be a problem with your [Watchman](https://facebook.github.io/watchman/) installation as described in [facebook/create-react-app#713](https://github.com/facebook/create-react-app/issues/713).
2495 |
2496 | 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:
2497 |
2498 | - [facebook/jest#1767](https://github.com/facebook/jest/issues/1767)
2499 | - [facebook/watchman#358](https://github.com/facebook/watchman/issues/358)
2500 | - [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259)
2501 |
2502 | 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:
2503 |
2504 | ```
2505 | watchman shutdown-server
2506 | brew update
2507 | brew reinstall watchman
2508 | ```
2509 |
2510 | You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page.
2511 |
2512 | If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
2513 |
2514 | There are also reports that _uninstalling_ Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
2515 |
2516 | ### `npm run build` exits too early
2517 |
2518 | It is reported that `npm run build` can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:
2519 |
2520 | > The build failed because the process exited too early. This probably means the system ran out of memory or someone called `kill -9` on the process.
2521 |
2522 | If you are completely sure that you didn't terminate the process, consider [adding some swap space](https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04) to the machine you’re building on, or build the project locally.
2523 |
2524 | ### `npm run build` fails on Heroku
2525 |
2526 | This may be a problem with case sensitive filenames.
2527 | Please refer to [this section](#resolving-heroku-deployment-errors).
2528 |
2529 | ### Moment.js locales are missing
2530 |
2531 | If you use a [Moment.js](https://momentjs.com/), you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of [all the locales provided by Moment.js](https://momentjs.com/#multiple-locale-support).
2532 |
2533 | To add a specific Moment.js locale to your bundle, you need to import it explicitly.
2534 | For example:
2535 |
2536 | ```js
2537 | import moment from 'moment';
2538 | import 'moment/locale/fr';
2539 | ```
2540 |
2541 | If you are importing multiple locales this way, you can later switch between them by calling `moment.locale()` with the locale name:
2542 |
2543 | ```js
2544 | import moment from 'moment';
2545 | import 'moment/locale/fr';
2546 | import 'moment/locale/es';
2547 |
2548 | // ...
2549 |
2550 | moment.locale('fr');
2551 | ```
2552 |
2553 | This will only work for locales that have been explicitly imported before.
2554 |
2555 | ### `npm run build` fails to minify
2556 |
2557 | Before `react-scripts@2.0.0`, this problem was caused by third party `node_modules` using modern JavaScript features because the minifier couldn't handle them during the build. This has been solved by compiling standard modern JavaScript features inside `node_modules` in `react-scripts@2.0.0` and higher.
2558 |
2559 | If you're seeing this error, you're likely using an old version of `react-scripts`. You can either fix it by avoiding a dependency that uses modern syntax, or by upgrading to `react-scripts@>=2.0.0` and following the migration instructions in the changelog.
2560 |
2561 | ## Alternatives to Ejecting
2562 |
2563 | [Ejecting](#npm-run-eject) lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to _fork_ `react-scripts` and any other packages you need. [This article](https://auth0.com/blog/how-to-configure-create-react-app/) dives into how to do it in depth. You can find more discussion in [this issue](https://github.com/facebook/create-react-app/issues/682).
2564 |
2565 | ## Something Missing?
2566 |
2567 | If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebook/create-react-app/issues) or [contribute some!](https://github.com/facebook/create-react-app/edit/master/packages/react-scripts/template/README.md)
2568 |
--------------------------------------------------------------------------------
/quizbiz/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "quizbiz",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "async-retry": "^1.2.3",
7 | "aws-amplify": "^1.1.7",
8 | "aws-amplify-react": "^2.1.1",
9 | "lodash": "^4.17.11",
10 | "react": "^16.6.0",
11 | "react-dom": "^16.6.0",
12 | "react-scripts": "2.0.5",
13 | "semantic-ui-css": "^2.4.1",
14 | "semantic-ui-react": "^0.83.0"
15 | },
16 | "scripts": {
17 | "start": "react-scripts start",
18 | "build": "react-scripts build",
19 | "test": "react-scripts test",
20 | "eject": "react-scripts eject"
21 | },
22 | "eslintConfig": {
23 | "extends": "react-app"
24 | },
25 | "browserslist": [
26 | ">0.2%",
27 | "not dead",
28 | "not ie <= 11",
29 | "not op_mini all"
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/quizbiz/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ACloudGuru-Resources/Course_Introduction_to_AWS_AppSync/6b06132d7eb38f8eff2310e7b68f57ede6149552/quizbiz/public/favicon.ico
--------------------------------------------------------------------------------
/quizbiz/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 | You need to enable JavaScript to run this app.
27 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/quizbiz/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/quizbiz/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Segment, Header, Container } from 'semantic-ui-react';
3 |
4 | import Amplify from 'aws-amplify';
5 | import { withAuthenticator } from 'aws-amplify-react';
6 |
7 | import Quiz from './components/Quiz';
8 | import QuizPicker from './components/QuizPicker';
9 |
10 | import aws_exports from './aws-exports';
11 | Amplify.configure(aws_exports);
12 | Amplify.Logger.LOG_LEVEL = 'INFO';
13 |
14 |
15 | class App extends React.Component {
16 | constructor(props) {
17 | super(props);
18 | this.state = {
19 | activeQuiz: null,
20 | };
21 | }
22 |
23 | async componentDidMount() {
24 | document.title = "QuizBiz";
25 | }
26 |
27 | setActiveQuiz = (i) => this.setState({activeQuiz: i});
28 |
29 | render() {
30 | return (
31 |
32 |
33 |
34 |
35 | Welcome to QuizBiz
36 |
37 |
38 |
39 |
40 |
43 |
45 |
46 |
47 | );
48 | }
49 | }
50 |
51 | export default App;
52 | //export default withAuthenticator(App);
--------------------------------------------------------------------------------
/quizbiz/src/components/Question.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Icon, Label, Form, Radio, Grid, Segment, Header } from 'semantic-ui-react';
3 |
4 | class Question extends React.Component {
5 | constructor(props) {
6 | super(props);
7 | this.state = {
8 | comment: '',
9 | answered: false,
10 | value: null,
11 | correct: false,
12 | }
13 | }
14 |
15 | // enforce the radio button getting checked
16 | updateRadio = (e, { value }) => this.setState({ value });
17 |
18 | submitAnswer = (e) => {
19 | this.props.question.answers.items.map(a => {
20 | if (this.state.value === a.id) {
21 | // user was right, set this question as correctly answered
22 | if (a.correct) {
23 | this.setState({correct: true});
24 | this.props.rightAnswer()
25 | }
26 | // show the comment
27 | if (a.comment) {
28 | this.setState({ comment: a.comment })
29 | } else {
30 | if (a.correct) {
31 | this.setState({ comment: "Great work!" })
32 | } else {
33 | this.setState({ comment: "Sorry, that's not it." })
34 | }
35 | }
36 | }
37 | return (this.state.value === a.id && a.correct)
38 | });
39 | this.setState({ answered: true });
40 | this.props.answer(this.props.question.id)
41 | };
42 |
43 | render() {
44 | return (
45 |
46 |
47 |
48 | {this.props.question.text}
49 |
50 | {this.state.answered &&
51 |
52 | {this.props.question.explanation === null ?
53 | {this.state.correct ? "Great work!" : "Sorry, that's not right"}
54 | :
55 | {this.props.question.explanation}
56 | }
57 | {this.props.question.links &&
58 |
59 | {this.props.question.links.map((l, index) =>
60 | {l}
61 | )}
62 |
63 | }
64 |
65 | }
66 |
67 | {(this.props.question.tags || []).map((t) => (
68 |
69 | {t}
70 | Topic
71 |
72 | ))}
73 |
74 |
75 |
76 |
92 |
93 |
94 | Submit
95 |
96 |
97 |
98 |
99 |
100 | );
101 | }
102 | }
103 |
104 | export default Question;
105 |
--------------------------------------------------------------------------------
/quizbiz/src/components/QuestionForm.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import _ from 'lodash';
3 | import { Icon, Form, } from 'semantic-ui-react';
4 |
5 | class QuestionForm extends Component {
6 | constructor(props) {
7 | super(props);
8 | this.state = {
9 | quizTitle: null,
10 | quizId: null,
11 | correctAnswer: null,
12 | questionText: null,
13 | questionExplanation: null,
14 | answerText1: null,
15 | answerText2: null,
16 | answerText3: null,
17 | answerText4: null,
18 | loading: false
19 | };
20 | }
21 |
22 | submit = () => {
23 | this.props.submit(this.state)
24 | this.setState({ loading: true })
25 | }
26 |
27 | updateCheck = (e, { value }) => {
28 | console.log({ event: e, value: value })
29 | this.setState({ correctAnswer: value })
30 | }
31 |
32 | updateText = (e, { name, value }) => {
33 | console.log({ event: e, name: name, value: value })
34 | this.setState({ [name]: value })
35 | }
36 |
37 | render() {
38 | return (
39 |
41 | Answers
42 | {_.map([1, 2, 3, 4], i => (
43 |
44 |
51 |
52 |
53 | ))}
54 |
55 |
56 | { return { text: v.title, value: v.id } })}
64 | />
65 |
69 |
70 |
71 |
77 |
78 | Submit
79 |
80 |
81 | )
82 | }
83 | }
84 |
85 | export default QuestionForm;
--------------------------------------------------------------------------------
/quizbiz/src/components/Quiz.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import _ from 'lodash';
3 | import { Grid, Progress} from 'semantic-ui-react';
4 |
5 | import { Cache, graphqlOperation } from 'aws-amplify';
6 | import { Connect } from 'aws-amplify-react';
7 |
8 | import Question from './Question';
9 |
10 | // Store answers for a day
11 | const AnswerCache = Cache.createInstance({ storage: window.sessionStorage, keyPrefix: 'answers', defaultTTL: 24*60*60*1000 });
12 |
13 | const ListQuizQuestions = `
14 | query MyQuestions ($quizID: ID!){
15 | getQuiz(id: $quizID) {
16 | questions (limit: 50) {
17 | items {
18 | id
19 | tags
20 | text
21 | explanation
22 | links
23 | answers {
24 | items { id text correct }
25 | }
26 | }
27 | }
28 | }
29 | }`;
30 |
31 | const ViewScore = ({totalAnswers, correctAnswers}) => {
32 | if (totalAnswers === 0) {
33 | return ''
34 | }
35 | let color = 'grey';
36 | if (correctAnswers/totalAnswers > .85) {
37 | color = 'green'
38 | } else if (correctAnswers/totalAnswers > .7) {
39 | color = 'teal'
40 | } else if (correctAnswers/totalAnswers > .6) {
41 | color = 'yellow'
42 | } else if (correctAnswers/totalAnswers > .4) {
43 | color = 'orange'
44 | }
45 | return (
46 |
47 | )
48 | };
49 |
50 |
51 | class Quiz extends React.Component {
52 | constructor(props) {
53 | super(props);
54 | //console.log('Read cache of answered question IDs', AnswerCache.getAllKeys());
55 | this.state = {
56 | questions: [],
57 | answeredIds: AnswerCache.getAllKeys() || [],
58 | totalAnswers: 0,
59 | correctAnswers: 0,
60 | };
61 | }
62 |
63 | answer = (qId) => {
64 | console.log('User answered', qId);
65 | AnswerCache.setItem(qId, 1);
66 | this.setState({
67 | totalAnswers: this.state.totalAnswers + 1,
68 | answeredIds: _.concat(this.state.answeredIds, [qId]),
69 | });
70 | };
71 |
72 | rightAnswer = () => this.setState({ correctAnswers: this.state.correctAnswers + 1 });
73 |
74 | unansweredQuestions = () => _.filter(
75 | this.state.questions, o => {
76 | // Filter out all questions that have been answered except the most recent question.
77 | return -1 === _.indexOf(this.state.answeredIds, o.id)
78 | }
79 | );
80 |
81 | scores = () =>
84 |
85 | render() {
86 | if (this.props.activeQuiz === null) return []
87 |
88 | return (
89 |
90 | {({ data, loading }) => {
91 | if (loading || data === null || data.getQuiz === undefined) return []
92 | return (
93 | {_.slice(
94 | _.filter(
95 | data.getQuiz.questions.items, o => {
96 | // Filter out all questions that have been answered except the most recent question.
97 | return -1 === _.indexOf(_.slice(this.state.answeredIds, 0, -1), o.id)
98 | }
99 | ),
100 | 0, 3
101 | ).map(q => (
102 |
103 | ))}
104 |
105 | )
106 | }}
107 |
108 | {this.scores()}
109 |
);
110 | }
111 | }
112 |
113 | export default Quiz;
114 |
--------------------------------------------------------------------------------
/quizbiz/src/components/QuizInput.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { graphqlOperation, API } from 'aws-amplify';
3 | import retry from 'async-retry';
4 | import _ from 'lodash';
5 | import { Modal, } from 'semantic-ui-react';
6 |
7 | import QuestionForm from './QuestionForm';
8 |
9 | const ActivateInput = (
10 | Add a Question
11 | )
12 |
13 | const QNewQuiz = `
14 | mutation (
15 | $title: String!,
16 | ) {
17 | createQuiz(input: {
18 | title: $title
19 | })
20 | {
21 | id
22 | title
23 | }
24 | }`;
25 |
26 | const QNewQuestion = `
27 | mutation (
28 | $text: String!,
29 | $explanation: String,
30 | $quizId: ID,
31 | ) {
32 | createQuestion(input: {
33 | text: $text,
34 | explanation: $explanation,
35 | quizQuestionsId: $quizId
36 | })
37 | {
38 | id
39 | text
40 | explanation
41 | }
42 | }`;
43 |
44 | const QNewAnswer = `
45 | mutation (
46 | $text: String,
47 | $correct: Boolean,
48 | $questionId: ID
49 | ) {
50 | createAnswer(input: {
51 | text: $text,
52 | correct: $correct,
53 | answerQuestionId: $questionId
54 | })
55 | {
56 | id
57 | }
58 | }`;
59 |
60 | const GqlRetry = async (query, variables) => {
61 | return await retry(
62 | async bail => {
63 | console.log('Sending GraphQL operation', {query: query, vars: variables});
64 | const response = await API.graphql(graphqlOperation(query, variables))
65 | console.log('GraphQL result', {result: response, query: query, vars: variables})
66 | return response
67 | },
68 | {
69 | retries: 10,
70 | }
71 | )
72 | };
73 |
74 | class QuizInput extends Component {
75 | constructor(props) {
76 | super(props);
77 | this.state = {
78 | correctAnswer: null,
79 | };
80 | }
81 |
82 | submitNewQuestion = async (input) => {
83 | console.log('New question submission', {event: input})
84 | let quizId = input.quizId
85 | if (input.quizTitle !== null) {
86 | const resp = await GqlRetry(QNewQuiz, {title: input.quizTitle});
87 | quizId = resp.data.createQuiz.id;
88 | }
89 | const newQ = await GqlRetry(QNewQuestion, {
90 | text: input.questionText,
91 | explanation: input.questionExplanation || '',
92 | quizId: quizId,
93 | })
94 | _.map(
95 | [input.answerText1, input.answerText2, input.answerText3, input.answerText4],
96 | (ans, idx) => {
97 | if (ans === null) return
98 | GqlRetry(QNewAnswer, {
99 | questionId: newQ.data.createQuestion.id,
100 | text: ans,
101 | correct: input.correctAnswer === 'answerText' + (idx+1),
102 | })
103 | }
104 | )
105 | }
106 |
107 | render() {
108 | return (
109 |
114 | Create a Question
115 |
116 |
117 |
118 |
119 | )
120 | }
121 | }
122 |
123 | export default QuizInput;
124 |
--------------------------------------------------------------------------------
/quizbiz/src/components/QuizPicker.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { graphqlOperation } from 'aws-amplify';
3 | import { Connect } from 'aws-amplify-react';
4 | import _ from 'lodash';
5 | import { Menu, Dropdown } from 'semantic-ui-react';
6 | import QuizInput from './QuizInput';
7 |
8 | const SubscribeToQuizzes = `
9 | subscription OnCreateQuiz {
10 | onCreateQuiz {
11 | id
12 | title
13 | }
14 | }
15 | `;
16 |
17 | const ListQuizzes = `
18 | query MyQuizzes {
19 | listQuizzes(limit: 5) {
20 | nextToken
21 | items {
22 | id
23 | title
24 | }
25 | }
26 | }`;
27 |
28 | class QuizPicker extends Component {
29 | constructor(props) {
30 | super(props);
31 | this.state = {
32 | modalActive: false,
33 | };
34 | }
35 |
36 | handleItemClick = (e, { name }) => {
37 | this.props.propagateQuiz(name)
38 | };
39 |
40 | closeModal = () => this.setState({modalActive: false})
41 | openModal = () => this.setState({modalActive: true})
42 | renderDropdowns = (data) => {
43 |
44 | if (data.listQuizzes.items.length === 0) {
45 | return []
46 | }
47 | return [
48 | ({
49 | this.props.activeQuiz ? _.head(_.filter(data.listQuizzes.items, q => q.id === this.props.activeQuiz)).title : 'Choose a quiz!'
50 | } ),
51 | (
52 |
53 | {_.map(_.filter(_.sortBy(data.listQuizzes.items, 'title'), q => q.id !== this.props.activeQuiz), q => {
54 | return (
55 | {q.title}
61 | )
62 | })}
63 |
64 | )
65 |
66 | ]
67 | }
68 | render() {
69 | return (
70 | {
74 | console.log("New quiz created:", {prev: prev, newData: data} );
75 | prev.listQuizzes.items = _.concat(prev.listQuizzes.items, [{
76 | id: data.onCreateQuiz.id,
77 | title: data.onCreateQuiz.title
78 | }])
79 | return prev
80 | }}
81 | >
82 | {({ data, loading }) => {
83 | if (loading || data === undefined || data === null || data.listQuizzes === undefined) return []
84 | return (
85 |
86 | {this.renderDropdowns(data)}
87 | {
92 |
97 | }
98 |
99 | )
100 | }
101 | }
102 |
103 | )
104 | }
105 | }
106 |
107 | export default QuizPicker;
108 |
--------------------------------------------------------------------------------
/quizbiz/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
6 | sans-serif;
7 | -webkit-font-smoothing: antialiased;
8 | -moz-osx-font-smoothing: grayscale;
9 | }
10 |
11 | code {
12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
13 | monospace;
14 | }
15 |
--------------------------------------------------------------------------------
/quizbiz/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import 'semantic-ui-css/semantic.min.css';
5 | import App from './App';
6 | import * as serviceWorker from './serviceWorker';
7 |
8 | ReactDOM.render( , document.getElementById('root'));
9 |
10 | // If you want your app to work offline and load faster, you can change
11 | // unregister() to register() below. Note this comes with some pitfalls.
12 | // Learn more about service workers: http://bit.ly/CRA-PWA
13 | serviceWorker.unregister();
14 |
--------------------------------------------------------------------------------
/quizbiz/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA.
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | installingWorker.onstatechange = () => {
64 | if (installingWorker.state === 'installed') {
65 | if (navigator.serviceWorker.controller) {
66 | // At this point, the updated precached content has been fetched,
67 | // but the previous service worker will still serve the older
68 | // content until all client tabs are closed.
69 | console.log(
70 | 'New content is available and will be used when all ' +
71 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
72 | );
73 |
74 | // Execute callback
75 | if (config && config.onUpdate) {
76 | config.onUpdate(registration);
77 | }
78 | } else {
79 | // At this point, everything has been precached.
80 | // It's the perfect time to display a
81 | // "Content is cached for offline use." message.
82 | console.log('Content is cached for offline use.');
83 |
84 | // Execute callback
85 | if (config && config.onSuccess) {
86 | config.onSuccess(registration);
87 | }
88 | }
89 | }
90 | };
91 | };
92 | })
93 | .catch(error => {
94 | console.error('Error during service worker registration:', error);
95 | });
96 | }
97 |
98 | function checkValidServiceWorker(swUrl, config) {
99 | // Check if the service worker can be found. If it can't reload the page.
100 | fetch(swUrl)
101 | .then(response => {
102 | // Ensure service worker exists, and that we really are getting a JS file.
103 | if (
104 | response.status === 404 ||
105 | response.headers.get('content-type').indexOf('javascript') === -1
106 | ) {
107 | // No service worker found. Probably a different app. Reload the page.
108 | navigator.serviceWorker.ready.then(registration => {
109 | registration.unregister().then(() => {
110 | window.location.reload();
111 | });
112 | });
113 | } else {
114 | // Service worker found. Proceed as normal.
115 | registerValidSW(swUrl, config);
116 | }
117 | })
118 | .catch(() => {
119 | console.log(
120 | 'No internet connection found. App is running in offline mode.'
121 | );
122 | });
123 | }
124 |
125 | export function unregister() {
126 | if ('serviceWorker' in navigator) {
127 | navigator.serviceWorker.ready.then(registration => {
128 | registration.unregister();
129 | });
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/schemas/application-schema.graphql:
--------------------------------------------------------------------------------
1 | type Question @model @versioned {
2 | id: ID!
3 | text: String!
4 | tags: [String]
5 | links: [String]
6 | explanation: String
7 | answers: [Answer] @connection(name: "QuestionChoices")
8 | }
9 |
10 | type Answer @model @versioned {
11 | id: ID!
12 | text: String
13 | correct: Boolean
14 | question: Question @connection(name: "QuestionChoices")
15 | }
16 |
17 | type Quiz @model(queries: {list: "listQuizzes", get: "getQuiz"}) @versioned {
18 | id: ID!
19 | title: String!
20 | questions: [Question] @connection
21 | }
22 |
--------------------------------------------------------------------------------
/schemas/list-questions.vtl.txt:
--------------------------------------------------------------------------------
1 | ## schemas/list-questions.vtl.txt
2 | {
3 | "version" : "2017-02-28",
4 | "operation" : "Scan",
5 | "limit": $util.defaultIfNull(${ctx.args.limit}, 20),
6 | "nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.nextToken, null))
7 | }
8 |
--------------------------------------------------------------------------------
/schemas/resolver-create-question.vtl.txt:
--------------------------------------------------------------------------------
1 | {
2 | "version" : "2017-02-28",
3 | "operation" : "PutItem",
4 | "key" : {
5 | ## If object "id" should come from GraphQL arguments, change to $util.dynamodb.toDynamoDBJson($ctx.args.id)
6 | "id": $util.dynamodb.toDynamoDBJson($util.autoId()),
7 | },
8 | "attributeValues" : $util.dynamodb.toMapValuesJson($ctx.args.input)
9 | }
10 |
--------------------------------------------------------------------------------
/schemas/resolver-get-question-by-id.vtl.txt:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2017-02-28",
3 | "operation": "GetItem",
4 | "key": {
5 | "id": $util.dynamodb.toDynamoDBJson($ctx.args.id),
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/schemas/simple-mutations.graphql:
--------------------------------------------------------------------------------
1 | type Question {
2 | id: ID!
3 | text: String!
4 | explanation: String
5 | answers: [AWSJSON]
6 | }
7 |
8 | type Query {
9 | getQuestion(id: ID!): Question
10 | }
11 |
12 | input CreateQuestionInput {
13 | text: String!
14 | explanation: String
15 | answers: [AWSJSON]
16 | }
17 |
18 | type Mutation {
19 | createQuestion(input: CreateQuestionInput!): Question
20 | }
21 |
--------------------------------------------------------------------------------
/schemas/simple-query.graphql:
--------------------------------------------------------------------------------
1 | type Question {
2 | id: ID!
3 | text: String!
4 | explanation: String
5 | answers: [AWSJSON]
6 | }
7 |
8 | type PaginatedQuestions {
9 | nextToken: String
10 | items: [Question]
11 | }
12 |
13 | type Query {
14 | getQuestion(id: ID!): Question
15 | listQuestions(limit: Int, nextToken: String): PaginatedQuestions
16 | }
17 |
18 | input CreateQuestionInput {
19 | text: String!
20 | explanation: String
21 | answers: [AWSJSON]
22 | }
23 |
24 | type Mutation {
25 | createQuestion(input: CreateQuestionInput!): Question
26 | }
27 |
--------------------------------------------------------------------------------
/schemas/test-queries.graphql:
--------------------------------------------------------------------------------
1 | # schemas/test-queries.graphql
2 | query GetQuestion {
3 | getQuestion(id: "e822ba66-17f9-477a-8a89-500839a35c21") {
4 | id
5 | text
6 | answers
7 | explanation
8 | }
9 | }
10 |
11 | mutation NewColorQuestion {
12 | createQuestion(input: {
13 | text: "What is your favorite color?",
14 | explanation: "Purple, of course!",
15 | answers: [
16 | "{\"text\": \"Orange\", \"correct\": false}",
17 | "{\"text\": \"Purple\", \"correct\": true}",
18 | "{\"text\": \"Yellow\", \"correct\": false}"
19 | ]
20 | }) {
21 | id
22 | answers
23 | text
24 | }
25 | }
26 |
27 | mutation NewServiceQuestion {
28 | createQuestion(input: {
29 | text: "What is your favorite AWS service?",
30 | explanation: "AppSync, what else?",
31 | answers: [
32 | "{\"text\": \"AWS Lambda\", \"correct\": false}",
33 | "{\"text\": \"AWS AppSync\", \"correct\": true}",
34 | "{\"text\": \"AWS S3\", \"correct\": false}"
35 | ]
36 | }) {
37 | id
38 | answers
39 | text
40 | }
41 | }
42 |
43 |
--------------------------------------------------------------------------------