├── .travis.yml ├── example ├── src │ ├── index.css │ ├── index.js │ ├── App.jsx │ └── components │ │ ├── Image.jsx │ │ ├── Download.jsx │ │ └── Text.js ├── public │ ├── manifest.json │ └── index.html ├── package.json └── README.md ├── docs ├── fonts │ ├── OpenSans-Bold-webfont.eot │ ├── OpenSans-Bold-webfont.woff │ ├── OpenSans-Italic-webfont.eot │ ├── OpenSans-Light-webfont.eot │ ├── OpenSans-Light-webfont.woff │ ├── OpenSans-Italic-webfont.woff │ ├── OpenSans-Regular-webfont.eot │ ├── OpenSans-Regular-webfont.woff │ ├── OpenSans-BoldItalic-webfont.eot │ ├── OpenSans-BoldItalic-webfont.woff │ ├── OpenSans-LightItalic-webfont.eot │ └── OpenSans-LightItalic-webfont.woff ├── scripts │ ├── linenumber.js │ └── prettify │ │ ├── lang-css.js │ │ ├── Apache-License-2.0.txt │ │ └── prettify.js ├── styles │ ├── prettify-jsdoc.css │ ├── prettify-tomorrow.css │ └── jsdoc-default.css ├── index.js.html ├── index.html └── global.html ├── .prettierrc ├── .babelrc ├── .editorconfig ├── .eslintrc.js ├── .gitignore ├── rollup.config.js ├── src ├── index.test.js └── index.js ├── README.md └── package.json /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 8 4 | env: 5 | - SKIP_PREFLIGHT_CHECK=true 6 | -------------------------------------------------------------------------------- /example/src/index.css: -------------------------------------------------------------------------------- 1 | /* body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | } */ 6 | -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Bold-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Bold-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Italic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Light-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Light-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Italic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Regular-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-Regular-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-BoldItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-BoldItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-LightItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vre2h/use-react-screenshot/HEAD/docs/fonts/OpenSans-LightItalic-webfont.woff -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "jsxSingleQuote": true, 5 | "arrowParens": "always", 6 | "trailingComma": "all" 7 | } 8 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["@babel/preset-env", { 4 | "modules": false 5 | }], 6 | "@babel/preset-react" 7 | ], 8 | "plugins": ["@babel/plugin-proposal-class-properties"] 9 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es6: true, 5 | jest: true, 6 | }, 7 | extends: ['airbnb-base'], 8 | rules: { 9 | semi: 0, 10 | }, 11 | } 12 | -------------------------------------------------------------------------------- /example/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom' 3 | 4 | import './index.css' 5 | import App from './App' 6 | 7 | ReactDOM.render(, document.getElementById('root')) 8 | -------------------------------------------------------------------------------- /example/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "use-react-screenshot", 3 | "name": "use-react-screenshot", 4 | "start_url": "./index.html", 5 | "display": "standalone", 6 | "theme_color": "#000000", 7 | "background_color": "#ffffff" 8 | } 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # See https://help.github.com/ignore-files/ for more about ignoring files. 3 | 4 | # dependencies 5 | node_modules 6 | 7 | # builds 8 | build 9 | dist 10 | .rpt2_cache 11 | 12 | # misc 13 | .DS_Store 14 | .env 15 | .env.local 16 | .env.development.local 17 | .env.test.local 18 | .env.production.local 19 | 20 | npm-debug.log* 21 | yarn-debug.log* 22 | yarn-error.log* 23 | -------------------------------------------------------------------------------- /example/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | use-react-screenshot 11 | 12 | 13 | 14 | 17 | 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel' 2 | import commonjs from 'rollup-plugin-commonjs' 3 | import external from 'rollup-plugin-peer-deps-external' 4 | import resolve from 'rollup-plugin-node-resolve' 5 | import url from 'rollup-plugin-url' 6 | 7 | import pkg from './package.json' 8 | 9 | export default { 10 | input: 'src/index.js', 11 | output: [ 12 | { 13 | file: pkg.main, 14 | format: 'cjs', 15 | sourcemap: true 16 | }, 17 | { 18 | file: pkg.module, 19 | format: 'es', 20 | sourcemap: true 21 | } 22 | ], 23 | plugins: [ 24 | external(), 25 | url({ exclude: ['**/*.svg'] }), 26 | babel({ 27 | exclude: 'node_modules/**' 28 | }), 29 | resolve(), 30 | commonjs() 31 | ] 32 | } 33 | -------------------------------------------------------------------------------- /docs/scripts/linenumber.js: -------------------------------------------------------------------------------- 1 | /*global document */ 2 | (() => { 3 | const source = document.getElementsByClassName('prettyprint source linenums'); 4 | let i = 0; 5 | let lineNumber = 0; 6 | let lineId; 7 | let lines; 8 | let totalLines; 9 | let anchorHash; 10 | 11 | if (source && source[0]) { 12 | anchorHash = document.location.hash.substring(1); 13 | lines = source[0].getElementsByTagName('li'); 14 | totalLines = lines.length; 15 | 16 | for (; i < totalLines; i++) { 17 | lineNumber++; 18 | lineId = `line${lineNumber}`; 19 | lines[i].id = lineId; 20 | if (lineId === anchorHash) { 21 | lines[i].className += ' selected'; 22 | } 23 | } 24 | } 25 | })(); 26 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-react-screenshot-example", 3 | "homepage": "https://vre2h.github.io/use-react-screenshot", 4 | "version": "0.0.0", 5 | "license": "MIT", 6 | "private": true, 7 | "dependencies": { 8 | "html2canvas": "^1.0.0-rc.5", 9 | "prop-types": "^15.6.2", 10 | "react": "file:../node_modules/react", 11 | "react-dom": "18.2.0", 12 | "react-router-dom": "^5.1.2", 13 | "react-scripts": "^5.0.1", 14 | "use-react-screenshot": "file:.." 15 | }, 16 | "scripts": { 17 | "start": "react-scripts start", 18 | "build": "react-scripts build", 19 | "test": "react-scripts test --env=jsdom", 20 | "eject": "react-scripts eject" 21 | }, 22 | "browserslist": [ 23 | ">0.2%", 24 | "not dead", 25 | "not ie <= 11", 26 | "not op_mini all" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /example/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom' 3 | 4 | import Download from './components/Download' 5 | import Image from './components/Image' 6 | 7 | export default () => { 8 | return ( 9 | 10 |

Examples

11 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 |
28 | ) 29 | } 30 | -------------------------------------------------------------------------------- /docs/scripts/prettify/lang-css.js: -------------------------------------------------------------------------------- 1 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", 2 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); 3 | -------------------------------------------------------------------------------- /src/index.test.js: -------------------------------------------------------------------------------- 1 | import { renderHook } from '@testing-library/react-hooks' 2 | 3 | import { createFileName, useScreenshot } from './index' 4 | 5 | describe('checking file name', () => { 6 | test('should be empty', () => { 7 | const actual = createFileName('', 'name') 8 | const expected = '' 9 | 10 | expect(actual).toBe(expected) 11 | }) 12 | 13 | test('should work properly', () => { 14 | const actual = createFileName('jpg', 'name') 15 | const expected = 'name.jpg' 16 | 17 | expect(actual).toBe(expected) 18 | }) 19 | }) 20 | 21 | describe('useScreenshot', () => { 22 | test('correct working of hook', async () => { 23 | const { 24 | result: { current }, 25 | } = renderHook(() => useScreenshot()) 26 | const [image, takeScreenShot, { error }] = current 27 | 28 | expect(error).toEqual(null) 29 | expect(image).toEqual(null) 30 | await expect(() => takeScreenShot()).toThrow() 31 | expect(error).toEqual(null) 32 | }) 33 | }) 34 | -------------------------------------------------------------------------------- /example/src/components/Image.jsx: -------------------------------------------------------------------------------- 1 | import React, { createRef, useState } from 'react' 2 | import { useScreenshot } from 'use-react-screenshot' 3 | import Text from './Text' 4 | 5 | export default () => { 6 | const ref = createRef(null) 7 | const [image, takeScreenShot] = useScreenshot() 8 | const [width, setWidth] = useState(300) 9 | 10 | const getImage = () => takeScreenShot(ref.current) 11 | 12 | return ( 13 |
14 |
15 | 18 | 22 |
23 | {'ScreenShot'} 24 |
32 | 33 |
34 |
35 | ) 36 | } 37 | -------------------------------------------------------------------------------- /example/src/components/Download.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, createRef } from 'react' 2 | import { useScreenshot, createFileName } from 'use-react-screenshot' 3 | import Text from './Text' 4 | 5 | export default () => { 6 | const ref = createRef(null) 7 | const [image, takeScreenShot] = useScreenshot() 8 | 9 | const download = (iImage, { name = 'img', extension = 'png' } = {}) => { 10 | const a = document.createElement('a') 11 | a.href = iImage 12 | a.download = createFileName(extension, name) 13 | a.click() 14 | } 15 | 16 | const getImage = () => takeScreenShot(ref.current) 17 | 18 | useEffect(() => { 19 | if (image) { 20 | download(image, { name: 'lorem-ipsum', extension: 'png' }) 21 | } 22 | }, [image]) 23 | 24 | return ( 25 |
26 | 27 |
35 | 36 |
37 |
38 | ) 39 | } 40 | -------------------------------------------------------------------------------- /docs/styles/prettify-jsdoc.css: -------------------------------------------------------------------------------- 1 | /* JSDoc prettify.js theme */ 2 | 3 | /* plain text */ 4 | .pln { 5 | color: #000000; 6 | font-weight: normal; 7 | font-style: normal; 8 | } 9 | 10 | /* string content */ 11 | .str { 12 | color: #006400; 13 | font-weight: normal; 14 | font-style: normal; 15 | } 16 | 17 | /* a keyword */ 18 | .kwd { 19 | color: #000000; 20 | font-weight: bold; 21 | font-style: normal; 22 | } 23 | 24 | /* a comment */ 25 | .com { 26 | font-weight: normal; 27 | font-style: italic; 28 | } 29 | 30 | /* a type name */ 31 | .typ { 32 | color: #000000; 33 | font-weight: normal; 34 | font-style: normal; 35 | } 36 | 37 | /* a literal value */ 38 | .lit { 39 | color: #006400; 40 | font-weight: normal; 41 | font-style: normal; 42 | } 43 | 44 | /* punctuation */ 45 | .pun { 46 | color: #000000; 47 | font-weight: bold; 48 | font-style: normal; 49 | } 50 | 51 | /* lisp open bracket */ 52 | .opn { 53 | color: #000000; 54 | font-weight: bold; 55 | font-style: normal; 56 | } 57 | 58 | /* lisp close bracket */ 59 | .clo { 60 | color: #000000; 61 | font-weight: bold; 62 | font-style: normal; 63 | } 64 | 65 | /* a markup tag name */ 66 | .tag { 67 | color: #006400; 68 | font-weight: normal; 69 | font-style: normal; 70 | } 71 | 72 | /* a markup attribute name */ 73 | .atn { 74 | color: #006400; 75 | font-weight: normal; 76 | font-style: normal; 77 | } 78 | 79 | /* a markup attribute value */ 80 | .atv { 81 | color: #006400; 82 | font-weight: normal; 83 | font-style: normal; 84 | } 85 | 86 | /* a declaration */ 87 | .dec { 88 | color: #000000; 89 | font-weight: bold; 90 | font-style: normal; 91 | } 92 | 93 | /* a variable name */ 94 | .var { 95 | color: #000000; 96 | font-weight: normal; 97 | font-style: normal; 98 | } 99 | 100 | /* a function name */ 101 | .fun { 102 | color: #000000; 103 | font-weight: bold; 104 | font-style: normal; 105 | } 106 | 107 | /* Specify class=linenums on a pre to get line numbering */ 108 | ol.linenums { 109 | margin-top: 0; 110 | margin-bottom: 0; 111 | } 112 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { useState } from 'react' 2 | import html2canvas from 'html2canvas' 3 | 4 | /** 5 | * @module Main_Hook 6 | * Hook return 7 | * @typedef {Array} HookReturn 8 | * @property {string} HookReturn[0] - image string 9 | * @property {string} HookReturn[1] - take screen shot string 10 | * @property {object} HookReturn[2] - errors 11 | */ 12 | 13 | /** 14 | * hook for creating screenshot from html node 15 | * @returns {HookReturn} 16 | */ 17 | const useScreenshot = ({ type, quality } = {}) => { 18 | const [image, setImage] = useState(null) 19 | const [error, setError] = useState(null) 20 | /** 21 | * convert html node to image 22 | * @param {HTMLElement} node 23 | * @param {Options} html2canvas options 24 | */ 25 | const takeScreenShot = (node, options = {}) => { 26 | if (!node) { 27 | throw new Error('You should provide correct html node.') 28 | } 29 | return html2canvas(node, options) 30 | .then((canvas) => { 31 | const croppedCanvas = document.createElement('canvas') 32 | const croppedCanvasContext = croppedCanvas.getContext('2d') 33 | // init data 34 | const cropPositionTop = 0 35 | const cropPositionLeft = 0 36 | const cropWidth = canvas.width 37 | const cropHeight = canvas.height 38 | 39 | croppedCanvas.width = cropWidth 40 | croppedCanvas.height = cropHeight 41 | 42 | croppedCanvasContext.drawImage( 43 | canvas, 44 | cropPositionLeft, 45 | cropPositionTop, 46 | ) 47 | 48 | const base64Image = croppedCanvas.toDataURL(type, quality) 49 | 50 | setImage(base64Image) 51 | return base64Image 52 | }) 53 | .catch(setError) 54 | } 55 | 56 | return [ 57 | image, 58 | takeScreenShot, 59 | { 60 | error, 61 | }, 62 | ] 63 | } 64 | 65 | /** 66 | * creates name of file 67 | * @param {string} extension 68 | * @param {string[]} parts of file name 69 | */ 70 | const createFileName = (extension = '', ...names) => { 71 | if (!extension) { 72 | return '' 73 | } 74 | 75 | return `${names.join('')}.${extension}` 76 | } 77 | 78 | export { useScreenshot, createFileName } 79 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Create react screenshot 2 | 3 | _React hook which allows you to make component screenshot and get an image in different extensions._ 4 | 5 | [![NPM](https://img.shields.io/npm/v/use-react-screenshot.svg)](https://www.npmjs.com/package/use-react-screenshot) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-airbnb-brightgreen.svg)](https://standardjs.com) [![Maintainability](https://api.codeclimate.com/v1/badges/4eed8edefb50d41a2093/maintainability)](https://codeclimate.com/github/vre2h/use-react-screenshot/maintainability) 6 | 7 | ## Install 8 | 9 | Note, this package has as `peerDependencies`: `react` and `html2canvas`. As we assume that you already have `react` installed, you can just install `html2canvas`. 10 | 11 | To install package run: 12 | ```bash 13 | npm install --save use-react-screenshot 14 | ``` 15 | 16 | To install `peerDependencies` run: 17 | ```bash 18 | npm install --save react html2canvas 19 | ``` 20 | 21 | ## Examples 22 | 23 | See this [codesandbox playground](https://codesandbox.io/s/react-screenshot-hook-2jdyt) or `/example` folder if you want to play with hook. 24 | 25 | In the following example you can find examples of: 26 | - Taking screenshot and placing it in your page 27 | - Downloaded screenshoted part 28 | - How to use different extensions (see `components/Download.js` page) 29 | 30 | ## Usage 31 | 32 | _A simple example which allows you to take a screenshot and place it as an image on the page (also you can download it or use differently, see examples section above)._ 33 | 34 | ```jsx 35 | import React, { useRef, useState } from 'react' 36 | import { useScreenshot } from 'use-react-screenshot' 37 | 38 | export default () => { 39 | const ref = useRef(null) 40 | const [image, takeScreenshot] = useScreenshot() 41 | const getImage = () => takeScreenshot(ref.current) 42 | return ( 43 |
44 |
45 | 48 |
49 | {'Screenshot'} 50 |
51 |

use-react-screenshot

52 |

53 | hook by @vre2h which allows to create screenshots 54 |

55 |
56 |
57 | ) 58 | } 59 | ``` 60 | 61 | ## License 62 | 63 | MIT © [vre2h](https://oganisyan.com) 64 | 65 | --- 66 | 67 | This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook). 68 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-react-screenshot", 3 | "version": "4.0.0", 4 | "description": "hook which allows to create screenshots", 5 | "author": "vre2h", 6 | "license": "MIT", 7 | "repository": "vre2h/use-react-screenshot", 8 | "main": "dist/index.js", 9 | "module": "dist/index.es.js", 10 | "jsnext:main": "dist/index.es.js", 11 | "engines": { 12 | "node": ">=8", 13 | "npm": ">=5" 14 | }, 15 | "scripts": { 16 | "test": "cross-env CI=1 react-scripts test --env=jsdom", 17 | "test:watch": "react-scripts test --env=jsdom", 18 | "build": "rollup -c", 19 | "start": "rollup -c -w", 20 | "prepare": "npx eslint src/ && npm run build", 21 | "docs": "npx jsdoc --readme ./README.md --destination ./docs src/" 22 | }, 23 | "peerDependencies": { 24 | "react": "^18.2.0", 25 | "html2canvas": "^1.3.3" 26 | }, 27 | "devDependencies": { 28 | "@babel/core": "^7.0.0", 29 | "@babel/plugin-external-helpers": "^7.0.0", 30 | "@babel/plugin-proposal-class-properties": "^7.0.0", 31 | "@babel/plugin-proposal-decorators": "^7.0.0", 32 | "@babel/plugin-proposal-do-expressions": "^7.0.0", 33 | "@babel/plugin-proposal-export-default-from": "^7.0.0", 34 | "@babel/plugin-proposal-export-namespace-from": "^7.0.0", 35 | "@babel/plugin-proposal-function-bind": "^7.0.0", 36 | "@babel/plugin-proposal-function-sent": "^7.0.0", 37 | "@babel/plugin-proposal-json-strings": "^7.0.0", 38 | "@babel/plugin-proposal-logical-assignment-operators": "^7.0.0", 39 | "@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0", 40 | "@babel/plugin-proposal-numeric-separator": "^7.0.0", 41 | "@babel/plugin-proposal-optional-chaining": "^7.0.0", 42 | "@babel/plugin-proposal-pipeline-operator": "^7.0.0", 43 | "@babel/plugin-proposal-throw-expressions": "^7.0.0", 44 | "@babel/plugin-syntax-dynamic-import": "^7.0.0", 45 | "@babel/plugin-syntax-import-meta": "^7.0.0", 46 | "@babel/preset-env": "^7.0.0", 47 | "@babel/preset-react": "^7.0.0", 48 | "@testing-library/react-hooks": "^3.2.1", 49 | "babel-eslint": "^10.0.1", 50 | "cross-env": "^5.2.0", 51 | "eslint": "^6.8.0", 52 | "eslint-config-airbnb-base": "^14.1.0", 53 | "eslint-plugin-import": "^2.20.1", 54 | "gh-pages": "^2.0.1", 55 | "html2canvas": "^1.3.3", 56 | "react": "^18.2.0", 57 | "react-scripts": "^3.4.0", 58 | "react-test-renderer": "^16.9.0", 59 | "rollup": "^1.1.2", 60 | "rollup-plugin-babel": "^4.3.2", 61 | "rollup-plugin-commonjs": "^9.2.0", 62 | "rollup-plugin-node-resolve": "^4.0.0", 63 | "rollup-plugin-peer-deps-external": "^2.2.0", 64 | "rollup-plugin-url": "^2.1.0" 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /docs/styles/prettify-tomorrow.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Theme */ 2 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 3 | /* Pretty printing styles. Used with prettify.js. */ 4 | /* SPAN elements with the classes below are added by prettyprint. */ 5 | /* plain text */ 6 | .pln { 7 | color: #4d4d4c; } 8 | 9 | @media screen { 10 | /* string content */ 11 | .str { 12 | color: #718c00; } 13 | 14 | /* a keyword */ 15 | .kwd { 16 | color: #8959a8; } 17 | 18 | /* a comment */ 19 | .com { 20 | color: #8e908c; } 21 | 22 | /* a type name */ 23 | .typ { 24 | color: #4271ae; } 25 | 26 | /* a literal value */ 27 | .lit { 28 | color: #f5871f; } 29 | 30 | /* punctuation */ 31 | .pun { 32 | color: #4d4d4c; } 33 | 34 | /* lisp open bracket */ 35 | .opn { 36 | color: #4d4d4c; } 37 | 38 | /* lisp close bracket */ 39 | .clo { 40 | color: #4d4d4c; } 41 | 42 | /* a markup tag name */ 43 | .tag { 44 | color: #c82829; } 45 | 46 | /* a markup attribute name */ 47 | .atn { 48 | color: #f5871f; } 49 | 50 | /* a markup attribute value */ 51 | .atv { 52 | color: #3e999f; } 53 | 54 | /* a declaration */ 55 | .dec { 56 | color: #f5871f; } 57 | 58 | /* a variable name */ 59 | .var { 60 | color: #c82829; } 61 | 62 | /* a function name */ 63 | .fun { 64 | color: #4271ae; } } 65 | /* Use higher contrast and text-weight for printable form. */ 66 | @media print, projection { 67 | .str { 68 | color: #060; } 69 | 70 | .kwd { 71 | color: #006; 72 | font-weight: bold; } 73 | 74 | .com { 75 | color: #600; 76 | font-style: italic; } 77 | 78 | .typ { 79 | color: #404; 80 | font-weight: bold; } 81 | 82 | .lit { 83 | color: #044; } 84 | 85 | .pun, .opn, .clo { 86 | color: #440; } 87 | 88 | .tag { 89 | color: #006; 90 | font-weight: bold; } 91 | 92 | .atn { 93 | color: #404; } 94 | 95 | .atv { 96 | color: #060; } } 97 | /* Style */ 98 | /* 99 | pre.prettyprint { 100 | background: white; 101 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 102 | font-size: 12px; 103 | line-height: 1.5; 104 | border: 1px solid #ccc; 105 | padding: 10px; } 106 | */ 107 | 108 | /* Specify class=linenums on a pre to get line numbering */ 109 | ol.linenums { 110 | margin-top: 0; 111 | margin-bottom: 0; } 112 | 113 | /* IE indents via margin-left */ 114 | li.L0, 115 | li.L1, 116 | li.L2, 117 | li.L3, 118 | li.L4, 119 | li.L5, 120 | li.L6, 121 | li.L7, 122 | li.L8, 123 | li.L9 { 124 | /* */ } 125 | 126 | /* Alternate shading for lines */ 127 | li.L1, 128 | li.L3, 129 | li.L5, 130 | li.L7, 131 | li.L9 { 132 | /* */ } 133 | -------------------------------------------------------------------------------- /docs/index.js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Source: index.js 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Source: index.js

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 |
import { useState } from 'react'
 30 | import html2canvas from 'html2canvas'
 31 | 
 32 | /**
 33 |  * @module Main_Hook
 34 |  * Hook return
 35 |  * @typedef {Array} HookReturn
 36 |  * @property {string} HookReturn[0] - image string
 37 |  * @property {string} HookReturn[1] - take screen shot string
 38 |  * @property {object} HookReturn[2] - errors
 39 |  */
 40 | 
 41 | /**
 42 |  * hook for creating screenshot from html node
 43 |  * @returns {HookReturn}
 44 |  */
 45 | const useScreenshot = ({ type, quality } = {}) => {
 46 |   const [image, setImage] = useState(null)
 47 |   const [error, setError] = useState(null)
 48 |   /**
 49 |    * convert html node to image
 50 |    * @param {HTMLElement} node
 51 |    * @param {Options} html2canvas options
 52 |    */
 53 |   const takeScreenShot = (node, options = {}) => {
 54 |     if (!node) {
 55 |       throw new Error('You should provide correct html node.')
 56 |     }
 57 |     return html2canvas(node, options)
 58 |       .then((canvas) => {
 59 |         const croppedCanvas = document.createElement('canvas')
 60 |         const croppedCanvasContext = croppedCanvas.getContext('2d')
 61 |         // init data
 62 |         const cropPositionTop = 0
 63 |         const cropPositionLeft = 0
 64 |         const cropWidth = canvas.width
 65 |         const cropHeight = canvas.height
 66 | 
 67 |         croppedCanvas.width = cropWidth
 68 |         croppedCanvas.height = cropHeight
 69 | 
 70 |         croppedCanvasContext.drawImage(
 71 |           canvas,
 72 |           cropPositionLeft,
 73 |           cropPositionTop,
 74 |         )
 75 | 
 76 |         const base64Image = croppedCanvas.toDataURL(type, quality)
 77 | 
 78 |         setImage(base64Image)
 79 |         return base64Image
 80 |       })
 81 |       .catch(setError)
 82 |   }
 83 | 
 84 |   return [
 85 |     image,
 86 |     takeScreenShot,
 87 |     {
 88 |       error,
 89 |     },
 90 |   ]
 91 | }
 92 | 
 93 | /**
 94 |  * creates name of file
 95 |  * @param {string} extension
 96 |  * @param  {string[]} parts of file name
 97 |  */
 98 | const createFileName = (extension = '', ...names) => {
 99 |   if (!extension) {
100 |     return ''
101 |   }
102 | 
103 |   return `${names.join('')}.${extension}`
104 | }
105 | 
106 | export { useScreenshot, createFileName }
107 | 
108 |
109 |
110 | 111 | 112 | 113 | 114 |
115 | 116 | 119 | 120 |
121 | 122 | 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /example/src/components/Text.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | export default () => ( 4 | <> 5 |

Lorem ipsum

6 |

What is Lorem Ipsum?

7 |

8 | Lorem Ipsum is simply dummy text of the printing and typesetting industry. 9 | Lorem Ipsum has been the industry's standard dummy text ever since the 10 | 1500s, when an unknown printer took a galley of type and scrambled it to 11 | make a type specimen book. It has survived not only five centuries, but 12 | also the leap into electronic typesetting, remaining essentially 13 | unchanged. It was popularised in the 1960s with the release of Letraset 14 | sheets containing Lorem Ipsum passages, and more recently with desktop 15 | publishing software like Aldus PageMaker including versions of Lorem 16 | Ipsum. 17 |

18 |

Why do we use it?

19 |

20 | It is a long established fact that a reader will be distracted by the 21 | readable content of a page when looking at its layout. The point of using 22 | Lorem Ipsum is that it has a more-or-less normal distribution of letters, 23 | as opposed to using 'Content here, content here', making it look like 24 | readable English. Many desktop publishing packages and web page editors 25 | now use Lorem Ipsum as their default model text, and a search for 'lorem 26 | ipsum' will uncover many web sites still in their infancy. Various 27 | versions have evolved over the years, sometimes by accident, sometimes on 28 | purpose (injected humour and the like). 29 |

30 |

Where does it come from?

31 |

32 | Contrary to popular belief, Lorem Ipsum is not simply random text. It has 33 | roots in a piece of classical Latin literature from 45 BC, making it over 34 | 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney 35 | College in Virginia, looked up one of the more obscure Latin words, 36 | consectetur, from a Lorem Ipsum passage, and going through the cites of 37 | the word in classical literature, discovered the undoubtable source. Lorem 38 | Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et 39 | Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This 40 | book is a treatise on the theory of ethics, very popular during the 41 | Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit 42 | amet..", comes from a line in section 1.10.32. The standard chunk of Lorem 43 | Ipsum used since the 1500s is reproduced below for those interested. 44 | Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by 45 | Cicero are also reproduced in their exact original form, accompanied by 46 | English versions from the 1914 translation by H. Rackham. 47 |

48 |

Where can I get some?

49 |

50 | There are many variations of passages of Lorem Ipsum available, but the 51 | majority have suffered alteration in some form, by injected humour, or 52 | randomised words which don't look even slightly believable. If you are 53 | going to use a passage of Lorem Ipsum, you need to be sure there isn't 54 | anything embarrassing hidden in the middle of text. All the Lorem Ipsum 55 | generators on the Internet tend to repeat predefined chunks as necessary, 56 | making this the first true generator on the Internet. It uses a dictionary 57 | of over 200 Latin words, combined with a handful of model sentence 58 | structures, to generate Lorem Ipsum which looks reasonable. The generated 59 | Lorem Ipsum is therefore always free from repetition, injected humour, or 60 | non-characteristic words etc. 61 |

62 | 63 | ) 64 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Home 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Home

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 |

Create react screenshot

47 |

React hook which allows you to make component screenshot and get an image in different extensions.

48 |

NPM JavaScript Style Guide Maintainability

49 |

Install

50 |

Note, this package has as peerDependencies: react and html2canvas. As we assume that you already have react installed, you can just install html2canvas.

51 |

To install package run:

52 |
npm install --save use-react-screenshot
 53 | 
54 |

To install peerDependencies run:

55 |
npm install --save react html2canvas
 56 | 
57 |

Examples

58 |

See this codesandbox playground or /example folder if you want to play with hook.

59 |

In the following example you can find examples of:

60 |
    61 |
  • Taking screenshot and placing it in your page
  • 62 |
  • Downloaded screenshoted part
  • 63 |
  • How to use different extensions (see components/Download.js page)
  • 64 |
65 |

Usage

66 |

A simple example which allows you to take a screenshot and place it as an image on the page (also you can download it or use differently, see examples section above).

67 |
import React, { useRef, useState } from 'react'
 68 | import { useScreenshot } from 'use-react-screenshot'
 69 | 
 70 | export default () => {
 71 |   const ref = useRef(null)
 72 |   const [image, takeScreenshot] = useScreenshot()
 73 |   const getImage = () => takeScreenshot(ref.current)
 74 |   return (
 75 |     <div>
 76 |       <div>
 77 |         <button style={{ marginBottom: '10px' }} onClick={getImage}>
 78 |           Take screenshot
 79 |         </button>
 80 |       </div>
 81 |       <img width={width} src={image} alt={'Screenshot'} />
 82 |       <div ref={ref}>
 83 |         <h1>use-react-screenshot</h1>
 84 |         <p>
 85 |           <strong>hook by @vre2h which allows to create screenshots</strong>
 86 |         </p>
 87 |       </div>
 88 |     </div>
 89 |   )
 90 | }
 91 | 
92 |

License

93 |

MIT © vre2h

94 |
95 |

This hook is created using create-react-hook.

96 |
97 | 98 | 99 | 100 | 101 | 102 | 103 |
104 | 105 | 108 | 109 |
110 | 111 | 114 | 115 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /docs/styles/jsdoc-default.css: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: 'Open Sans'; 3 | font-weight: normal; 4 | font-style: normal; 5 | src: url('../fonts/OpenSans-Regular-webfont.eot'); 6 | src: 7 | local('Open Sans'), 8 | local('OpenSans'), 9 | url('../fonts/OpenSans-Regular-webfont.eot?#iefix') format('embedded-opentype'), 10 | url('../fonts/OpenSans-Regular-webfont.woff') format('woff'), 11 | url('../fonts/OpenSans-Regular-webfont.svg#open_sansregular') format('svg'); 12 | } 13 | 14 | @font-face { 15 | font-family: 'Open Sans Light'; 16 | font-weight: normal; 17 | font-style: normal; 18 | src: url('../fonts/OpenSans-Light-webfont.eot'); 19 | src: 20 | local('Open Sans Light'), 21 | local('OpenSans Light'), 22 | url('../fonts/OpenSans-Light-webfont.eot?#iefix') format('embedded-opentype'), 23 | url('../fonts/OpenSans-Light-webfont.woff') format('woff'), 24 | url('../fonts/OpenSans-Light-webfont.svg#open_sanslight') format('svg'); 25 | } 26 | 27 | html 28 | { 29 | overflow: auto; 30 | background-color: #fff; 31 | font-size: 14px; 32 | } 33 | 34 | body 35 | { 36 | font-family: 'Open Sans', sans-serif; 37 | line-height: 1.5; 38 | color: #4d4e53; 39 | background-color: white; 40 | } 41 | 42 | a, a:visited, a:active { 43 | color: #0095dd; 44 | text-decoration: none; 45 | } 46 | 47 | a:hover { 48 | text-decoration: underline; 49 | } 50 | 51 | header 52 | { 53 | display: block; 54 | padding: 0px 4px; 55 | } 56 | 57 | tt, code, kbd, samp { 58 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 59 | } 60 | 61 | .class-description { 62 | font-size: 130%; 63 | line-height: 140%; 64 | margin-bottom: 1em; 65 | margin-top: 1em; 66 | } 67 | 68 | .class-description:empty { 69 | margin: 0; 70 | } 71 | 72 | #main { 73 | float: left; 74 | width: 70%; 75 | } 76 | 77 | article dl { 78 | margin-bottom: 40px; 79 | } 80 | 81 | article img { 82 | max-width: 100%; 83 | } 84 | 85 | section 86 | { 87 | display: block; 88 | background-color: #fff; 89 | padding: 12px 24px; 90 | border-bottom: 1px solid #ccc; 91 | margin-right: 30px; 92 | } 93 | 94 | .variation { 95 | display: none; 96 | } 97 | 98 | .signature-attributes { 99 | font-size: 60%; 100 | color: #aaa; 101 | font-style: italic; 102 | font-weight: lighter; 103 | } 104 | 105 | nav 106 | { 107 | display: block; 108 | float: right; 109 | margin-top: 28px; 110 | width: 30%; 111 | box-sizing: border-box; 112 | border-left: 1px solid #ccc; 113 | padding-left: 16px; 114 | } 115 | 116 | nav ul { 117 | font-family: 'Lucida Grande', 'Lucida Sans Unicode', arial, sans-serif; 118 | font-size: 100%; 119 | line-height: 17px; 120 | padding: 0; 121 | margin: 0; 122 | list-style-type: none; 123 | } 124 | 125 | nav ul a, nav ul a:visited, nav ul a:active { 126 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 127 | line-height: 18px; 128 | color: #4D4E53; 129 | } 130 | 131 | nav h3 { 132 | margin-top: 12px; 133 | } 134 | 135 | nav li { 136 | margin-top: 6px; 137 | } 138 | 139 | footer { 140 | display: block; 141 | padding: 6px; 142 | margin-top: 12px; 143 | font-style: italic; 144 | font-size: 90%; 145 | } 146 | 147 | h1, h2, h3, h4 { 148 | font-weight: 200; 149 | margin: 0; 150 | } 151 | 152 | h1 153 | { 154 | font-family: 'Open Sans Light', sans-serif; 155 | font-size: 48px; 156 | letter-spacing: -2px; 157 | margin: 12px 24px 20px; 158 | } 159 | 160 | h2, h3.subsection-title 161 | { 162 | font-size: 30px; 163 | font-weight: 700; 164 | letter-spacing: -1px; 165 | margin-bottom: 12px; 166 | } 167 | 168 | h3 169 | { 170 | font-size: 24px; 171 | letter-spacing: -0.5px; 172 | margin-bottom: 12px; 173 | } 174 | 175 | h4 176 | { 177 | font-size: 18px; 178 | letter-spacing: -0.33px; 179 | margin-bottom: 12px; 180 | color: #4d4e53; 181 | } 182 | 183 | h5, .container-overview .subsection-title 184 | { 185 | font-size: 120%; 186 | font-weight: bold; 187 | letter-spacing: -0.01em; 188 | margin: 8px 0 3px 0; 189 | } 190 | 191 | h6 192 | { 193 | font-size: 100%; 194 | letter-spacing: -0.01em; 195 | margin: 6px 0 3px 0; 196 | font-style: italic; 197 | } 198 | 199 | table 200 | { 201 | border-spacing: 0; 202 | border: 0; 203 | border-collapse: collapse; 204 | } 205 | 206 | td, th 207 | { 208 | border: 1px solid #ddd; 209 | margin: 0px; 210 | text-align: left; 211 | vertical-align: top; 212 | padding: 4px 6px; 213 | display: table-cell; 214 | } 215 | 216 | thead tr 217 | { 218 | background-color: #ddd; 219 | font-weight: bold; 220 | } 221 | 222 | th { border-right: 1px solid #aaa; } 223 | tr > th:last-child { border-right: 1px solid #ddd; } 224 | 225 | .ancestors, .attribs { color: #999; } 226 | .ancestors a, .attribs a 227 | { 228 | color: #999 !important; 229 | text-decoration: none; 230 | } 231 | 232 | .clear 233 | { 234 | clear: both; 235 | } 236 | 237 | .important 238 | { 239 | font-weight: bold; 240 | color: #950B02; 241 | } 242 | 243 | .yes-def { 244 | text-indent: -1000px; 245 | } 246 | 247 | .type-signature { 248 | color: #aaa; 249 | } 250 | 251 | .name, .signature { 252 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 253 | } 254 | 255 | .details { margin-top: 14px; border-left: 2px solid #DDD; } 256 | .details dt { width: 120px; float: left; padding-left: 10px; padding-top: 6px; } 257 | .details dd { margin-left: 70px; } 258 | .details ul { margin: 0; } 259 | .details ul { list-style-type: none; } 260 | .details li { margin-left: 30px; padding-top: 6px; } 261 | .details pre.prettyprint { margin: 0 } 262 | .details .object-value { padding-top: 0; } 263 | 264 | .description { 265 | margin-bottom: 1em; 266 | margin-top: 1em; 267 | } 268 | 269 | .code-caption 270 | { 271 | font-style: italic; 272 | font-size: 107%; 273 | margin: 0; 274 | } 275 | 276 | .source 277 | { 278 | border: 1px solid #ddd; 279 | width: 80%; 280 | overflow: auto; 281 | } 282 | 283 | .prettyprint.source { 284 | width: inherit; 285 | } 286 | 287 | .source code 288 | { 289 | font-size: 100%; 290 | line-height: 18px; 291 | display: block; 292 | padding: 4px 12px; 293 | margin: 0; 294 | background-color: #fff; 295 | color: #4D4E53; 296 | } 297 | 298 | .prettyprint code span.line 299 | { 300 | display: inline-block; 301 | } 302 | 303 | .prettyprint.linenums 304 | { 305 | padding-left: 70px; 306 | -webkit-user-select: none; 307 | -moz-user-select: none; 308 | -ms-user-select: none; 309 | user-select: none; 310 | } 311 | 312 | .prettyprint.linenums ol 313 | { 314 | padding-left: 0; 315 | } 316 | 317 | .prettyprint.linenums li 318 | { 319 | border-left: 3px #ddd solid; 320 | } 321 | 322 | .prettyprint.linenums li.selected, 323 | .prettyprint.linenums li.selected * 324 | { 325 | background-color: lightyellow; 326 | } 327 | 328 | .prettyprint.linenums li * 329 | { 330 | -webkit-user-select: text; 331 | -moz-user-select: text; 332 | -ms-user-select: text; 333 | user-select: text; 334 | } 335 | 336 | .params .name, .props .name, .name code { 337 | color: #4D4E53; 338 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 339 | font-size: 100%; 340 | } 341 | 342 | .params td.description > p:first-child, 343 | .props td.description > p:first-child 344 | { 345 | margin-top: 0; 346 | padding-top: 0; 347 | } 348 | 349 | .params td.description > p:last-child, 350 | .props td.description > p:last-child 351 | { 352 | margin-bottom: 0; 353 | padding-bottom: 0; 354 | } 355 | 356 | .disabled { 357 | color: #454545; 358 | } 359 | -------------------------------------------------------------------------------- /docs/global.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Global 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Global

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

32 | 33 | 34 |
35 | 36 |
37 |
38 | 39 | 40 | 41 | 42 | 43 | 44 |
45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 |
78 | 79 | 80 | 81 | 82 |
83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 |

Methods

100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 |

createFileName(extension, parts)

108 | 109 | 110 | 111 | 112 | 113 | 114 |
115 | creates name of file 116 |
117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 |
Parameters:
127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 |
NameTypeDescription
extension 155 | 156 | 157 | string 158 | 159 | 160 | 161 |
parts 178 | 179 | 180 | Array.<string> 181 | 182 | 183 | 184 | of file name
196 | 197 | 198 | 199 | 200 | 201 | 202 |
203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 |
Source:
230 |
233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 |
241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 |

useScreenshot() → {HookReturn}

268 | 269 | 270 | 271 | 272 | 273 | 274 |
275 | hook for creating screenshot from html node 276 |
277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 |
291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 |
Source:
318 |
321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 |
329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 |
Returns:
345 | 346 | 347 | 348 | 349 |
350 |
351 | Type 352 |
353 |
354 | 355 | HookReturn 356 | 357 | 358 |
359 |
360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 |

Type Definitions

372 | 373 | 374 | 375 |

HookReturn

376 | 377 | 378 | 379 | 380 | 381 | 382 |
Type:
383 |
    384 |
  • 385 | 386 | Array 387 | 388 | 389 |
  • 390 |
391 | 392 | 393 | 394 | 395 | 396 |
Properties:
397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 |
NameTypeDescription
HookReturn[0 426 | 427 | 428 | string 429 | 430 | 431 | 432 | image string
HookReturn[1 449 | 450 | 451 | string 452 | 453 | 454 | 455 | take screen shot string
HookReturn[2 472 | 473 | 474 | object 475 | 476 | 477 | 478 | errors
490 | 491 | 492 | 493 | 494 |
495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 |
Source:
522 |
525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 |
533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 |
544 | 545 |
546 | 547 | 548 | 549 | 550 |
551 | 552 | 555 | 556 |
557 | 558 | 561 | 562 | 563 | 564 | 565 | -------------------------------------------------------------------------------- /docs/scripts/prettify/Apache-License-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /docs/scripts/prettify/prettify.js: -------------------------------------------------------------------------------- 1 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; 2 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= 3 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), 9 | l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, 10 | q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, 11 | q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, 12 | "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), 13 | a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} 14 | for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], 18 | "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], 19 | H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], 20 | J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ 21 | I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), 22 | ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", 23 | /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), 24 | ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", 25 | hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= 26 | !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p 4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 5 | 6 | ## Table of Contents 7 | 8 | - [Table of Contents](#table-of-contents) 9 | - [Updating to New Releases](#updating-to-new-releases) 10 | - [Sending Feedback](#sending-feedback) 11 | - [Folder Structure](#folder-structure) 12 | - [Available Scripts](#available-scripts) 13 | - [`npm start`](#npm-start) 14 | - [`npm test`](#npm-test) 15 | - [`npm run build`](#npm-run-build) 16 | - [`npm run eject`](#npm-run-eject) 17 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 18 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 19 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 20 | - [Debugging in the Editor](#debugging-in-the-editor) 21 | - [Visual Studio Code](#visual-studio-code) 22 | - [WebStorm](#webstorm) 23 | - [Formatting Code Automatically](#formatting-code-automatically) 24 | - [Changing the Page ``](#changing-the-page-title) 25 | - [Installing a Dependency](#installing-a-dependency) 26 | - [Importing a Component](#importing-a-component) 27 | - [`Button.js`](#buttonjs) 28 | - [`DangerButton.js`](#dangerbuttonjs) 29 | - [Code Splitting](#code-splitting) 30 | - [`moduleA.js`](#moduleajs) 31 | - [`App.js`](#appjs) 32 | - [With React Router](#with-react-router) 33 | - [Adding a Stylesheet](#adding-a-stylesheet) 34 | - [`Button.css`](#buttoncss) 35 | - [`Button.js`](#buttonjs-1) 36 | - [Using the `public` Folder](#using-the-public-folder) 37 | - [Changing the HTML](#changing-the-html) 38 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 39 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 40 | - [Using Global Variables](#using-global-variables) 41 | - [Adding Bootstrap](#adding-bootstrap) 42 | - [Using a Custom Theme](#using-a-custom-theme) 43 | - [Adding Flow](#adding-flow) 44 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 45 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 46 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 47 | - [Windows (cmd.exe)](#windows-cmdexe) 48 | - [Linux, macOS (Bash)](#linux-macos-bash) 49 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 50 | - [What other `.env` files are can be used?](#what-other-env-files-are-can-be-used) 51 | - [Can I Use Decorators?](#can-i-use-decorators) 52 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 53 | - [Node](#node) 54 | - [Ruby on Rails](#ruby-on-rails) 55 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 56 | - ["Invalid Host Header" Errors After Configuring Proxy](#%22invalid-host-header%22-errors-after-configuring-proxy) 57 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 58 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy) 59 | - [Using HTTPS in Development](#using-https-in-development) 60 | - [Windows (cmd.exe)](#windows-cmdexe-1) 61 | - [Linux, macOS (Bash)](#linux-macos-bash-1) 62 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 63 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 64 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 65 | - [Running Tests](#running-tests) 66 | - [Filename Conventions](#filename-conventions) 67 | - [Command Line Interface](#command-line-interface) 68 | - [Version Control Integration](#version-control-integration) 69 | - [Writing Tests](#writing-tests) 70 | - [Testing Components](#testing-components) 71 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 72 | - [Initializing Test Environment](#initializing-test-environment) 73 | - [`src/setupTests.js`](#srcsetuptestsjs) 74 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 75 | - [Coverage Reporting](#coverage-reporting) 76 | - [Continuous Integration](#continuous-integration) 77 | - [On CI servers](#on-ci-servers) 78 | - [Travis CI](#travis-ci) 79 | - [CircleCI](#circleci) 80 | - [On your own environment](#on-your-own-environment) 81 | - [Windows (cmd.exe)](#windows-cmdexe-2) 82 | - [Linux, macOS (Bash)](#linux-macos-bash-2) 83 | - [Disabling jsdom](#disabling-jsdom) 84 | - [Snapshot Testing](#snapshot-testing) 85 | - [Editor Integration](#editor-integration) 86 | - [Developing Components in Isolation](#developing-components-in-isolation) 87 | - [Getting Started with Storybook](#getting-started-with-storybook) 88 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 89 | - [Making a Progressive Web App](#making-a-progressive-web-app) 90 | - [Opting Out of Caching](#opting-out-of-caching) 91 | - [Offline-First Considerations](#offline-first-considerations) 92 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 93 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 94 | - [Deployment](#deployment) 95 | - [Static Server](#static-server) 96 | - [Other Solutions](#other-solutions) 97 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 98 | - [Building for Relative Paths](#building-for-relative-paths) 99 | - [Serving the Same Build from Different Paths](#serving-the-same-build-from-different-paths) 100 | - [Azure](#azure) 101 | - [Firebase](#firebase) 102 | - [GitHub Pages](#github-pages) 103 | - [Step 1: Add `homepage` to `package.json`](#step-1-add-homepage-to-packagejson) 104 | - [Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`](#step-2-install-gh-pages-and-add-deploy-to-scripts-in-packagejson) 105 | - [Step 3: Deploy the site by running `npm run deploy`](#step-3-deploy-the-site-by-running-npm-run-deploy) 106 | - [Step 4: Ensure your project’s settings use `gh-pages`](#step-4-ensure-your-projects-settings-use-gh-pages) 107 | - [Step 5: Optionally, configure the domain](#step-5-optionally-configure-the-domain) 108 | - [Notes on client-side routing](#notes-on-client-side-routing) 109 | - [Heroku](#heroku) 110 | - [Resolving Heroku Deployment Errors](#resolving-heroku-deployment-errors) 111 | - ["Module not found: Error: Cannot resolve 'file' or 'directory'"](#%22module-not-found-error-cannot-resolve-file-or-directory%22) 112 | - ["Could not find a required file."](#%22could-not-find-a-required-file%22) 113 | - [Netlify](#netlify) 114 | - [Now](#now) 115 | - [S3 and CloudFront](#s3-and-cloudfront) 116 | - [Surge](#surge) 117 | - [Advanced Configuration](#advanced-configuration) 118 | - [Troubleshooting](#troubleshooting) 119 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 120 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 121 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 122 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 123 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 124 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) 125 | - [Something Missing?](#something-missing) 126 | 127 | ## Updating to New Releases 128 | 129 | Create React App is divided into two packages: 130 | 131 | * `create-react-app` is a global command-line utility that you use to create new projects. 132 | * `react-scripts` is a development dependency in the generated projects (including this one). 133 | 134 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 135 | 136 | 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. 137 | 138 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 139 | 140 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 141 | 142 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 143 | 144 | ## Sending Feedback 145 | 146 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 147 | 148 | ## Folder Structure 149 | 150 | After creation, your project should look like this: 151 | 152 | ``` 153 | my-app/ 154 | README.md 155 | node_modules/ 156 | package.json 157 | public/ 158 | index.html 159 | favicon.ico 160 | src/ 161 | App.css 162 | App.js 163 | App.test.js 164 | index.css 165 | index.js 166 | logo.svg 167 | ``` 168 | 169 | For the project to build, **these files must exist with exact filenames**: 170 | 171 | * `public/index.html` is the page template; 172 | * `src/index.js` is the JavaScript entry point. 173 | 174 | You can delete or rename the other files. 175 | 176 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 177 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 178 | 179 | Only files inside `public` can be used from `public/index.html`.<br> 180 | Read instructions below for using assets from JavaScript and HTML. 181 | 182 | You can, however, create more top-level directories.<br> 183 | They will not be included in the production build so you can use them for things like documentation. 184 | 185 | ## Available Scripts 186 | 187 | In the project directory, you can run: 188 | 189 | ### `npm start` 190 | 191 | Runs the app in the development mode.<br> 192 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 193 | 194 | The page will reload if you make edits.<br> 195 | You will also see any lint errors in the console. 196 | 197 | ### `npm test` 198 | 199 | Launches the test runner in the interactive watch mode.<br> 200 | See the section about [running tests](#running-tests) for more information. 201 | 202 | ### `npm run build` 203 | 204 | Builds the app for production to the `build` folder.<br> 205 | It correctly bundles React in production mode and optimizes the build for the best performance. 206 | 207 | The build is minified and the filenames include the hashes.<br> 208 | Your app is ready to be deployed! 209 | 210 | See the section about [deployment](#deployment) for more information. 211 | 212 | ### `npm run eject` 213 | 214 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 215 | 216 | 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. 217 | 218 | 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. 219 | 220 | 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. 221 | 222 | ## Supported Language Features and Polyfills 223 | 224 | This project supports a superset of the latest JavaScript standard.<br> 225 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 226 | 227 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 228 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 229 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 230 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 231 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). 232 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 233 | 234 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 235 | 236 | While we recommend to use 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. 237 | 238 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 239 | 240 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 241 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 242 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 243 | 244 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. 245 | 246 | ## Syntax Highlighting in the Editor 247 | 248 | 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. 249 | 250 | ## Displaying Lint Output in the Editor 251 | 252 | >Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 253 | >It also only works with npm 3 or higher. 254 | 255 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 256 | 257 | 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. 258 | 259 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 260 | 261 | ```js 262 | { 263 | "extends": "react-app" 264 | } 265 | ``` 266 | 267 | Now your editor should report the linting warnings. 268 | 269 | 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. 270 | 271 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 272 | 273 | ## Debugging in the Editor 274 | 275 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** 276 | 277 | 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. 278 | 279 | ### Visual Studio Code 280 | 281 | 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. 282 | 283 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 284 | 285 | ```json 286 | { 287 | "version": "0.2.0", 288 | "configurations": [{ 289 | "name": "Chrome", 290 | "type": "chrome", 291 | "request": "launch", 292 | "url": "http://localhost:3000", 293 | "webRoot": "${workspaceRoot}/src", 294 | "userDataDir": "${workspaceRoot}/.vscode/chrome", 295 | "sourceMapPathOverrides": { 296 | "webpack:///src/*": "${webRoot}/*" 297 | } 298 | }] 299 | } 300 | ``` 301 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 302 | 303 | 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. 304 | 305 | ### WebStorm 306 | 307 | 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. 308 | 309 | 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. 310 | 311 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 312 | 313 | 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. 314 | 315 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. 316 | 317 | ## Formatting Code Automatically 318 | 319 | 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/). 320 | 321 | To format our code whenever we make a commit in git, we need to install the following dependencies: 322 | 323 | ```sh 324 | npm install --save husky lint-staged prettier 325 | ``` 326 | 327 | Alternatively you may use `yarn`: 328 | 329 | ```sh 330 | yarn add husky lint-staged prettier 331 | ``` 332 | 333 | * `husky` makes it easy to use githooks as if they are npm scripts. 334 | * `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). 335 | * `prettier` is the JavaScript formatter we will run before commits. 336 | 337 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 338 | 339 | Add the following line to `scripts` section: 340 | 341 | ```diff 342 | "scripts": { 343 | + "precommit": "lint-staged", 344 | "start": "react-scripts start", 345 | "build": "react-scripts build", 346 | ``` 347 | 348 | Next we add a 'lint-staged' field to the `package.json`, for example: 349 | 350 | ```diff 351 | "dependencies": { 352 | // ... 353 | }, 354 | + "lint-staged": { 355 | + "src/**/*.{js,jsx,json,css}": [ 356 | + "prettier --single-quote --write", 357 | + "git add" 358 | + ] 359 | + }, 360 | "scripts": { 361 | ``` 362 | 363 | 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. 364 | 365 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page. 366 | 367 | ## Changing the Page `<title>` 368 | 369 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 370 | 371 | 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. 372 | 373 | 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. 374 | 375 | 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). 376 | 377 | ## Installing a Dependency 378 | 379 | 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`: 380 | 381 | ```sh 382 | npm install --save react-router 383 | ``` 384 | 385 | Alternatively you may use `yarn`: 386 | 387 | ```sh 388 | yarn add react-router 389 | ``` 390 | 391 | This works for any library, not just `react-router`. 392 | 393 | ## Importing a Component 394 | 395 | This project setup supports ES6 modules thanks to Babel.<br> 396 | 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. 397 | 398 | For example: 399 | 400 | ### `Button.js` 401 | 402 | ```js 403 | import React, { Component } from 'react'; 404 | 405 | class Button extends Component { 406 | render() { 407 | // ... 408 | } 409 | } 410 | 411 | export default Button; // Don’t forget to use export default! 412 | ``` 413 | 414 | ### `DangerButton.js` 415 | 416 | 417 | ```js 418 | import React, { Component } from 'react'; 419 | import Button from './Button'; // Import a component from another file 420 | 421 | class DangerButton extends Component { 422 | render() { 423 | return <Button color="red" />; 424 | } 425 | } 426 | 427 | export default DangerButton; 428 | ``` 429 | 430 | 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. 431 | 432 | 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'`. 433 | 434 | 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. 435 | 436 | Learn more about ES6 modules: 437 | 438 | * [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) 439 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 440 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 441 | 442 | ## Code Splitting 443 | 444 | 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. 445 | 446 | 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. 447 | 448 | Here is an example: 449 | 450 | ### `moduleA.js` 451 | 452 | ```js 453 | const moduleA = 'Hello'; 454 | 455 | export { moduleA }; 456 | ``` 457 | ### `App.js` 458 | 459 | ```js 460 | import React, { Component } from 'react'; 461 | 462 | class App extends Component { 463 | handleClick = () => { 464 | import('./moduleA') 465 | .then(({ moduleA }) => { 466 | // Use moduleA 467 | }) 468 | .catch(err => { 469 | // Handle failure 470 | }); 471 | }; 472 | 473 | render() { 474 | return ( 475 | <div> 476 | <button onClick={this.handleClick}>Load</button> 477 | </div> 478 | ); 479 | } 480 | } 481 | 482 | export default App; 483 | ``` 484 | 485 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 486 | 487 | You can also use it with `async` / `await` syntax if you prefer it. 488 | 489 | ### With React Router 490 | 491 | 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). 492 | 493 | ## Adding a Stylesheet 494 | 495 | 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**: 496 | 497 | ### `Button.css` 498 | 499 | ```css 500 | .Button { 501 | padding: 20px; 502 | } 503 | ``` 504 | 505 | ### `Button.js` 506 | 507 | ```js 508 | import React, { Component } from 'react'; 509 | import './Button.css'; // Tell Webpack that Button.js uses these styles 510 | 511 | class Button extends Component { 512 | render() { 513 | // You can use them as regular CSS styles 514 | return <div className="Button" />; 515 | } 516 | } 517 | ``` 518 | 519 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 520 | 521 | 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. 522 | 523 | 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. 524 | 525 | ## Using the `public` Folder 526 | 527 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 528 | 529 | ### Changing the HTML 530 | 531 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 532 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 533 | 534 | ### Adding Assets Outside of the Module System 535 | 536 | You can also add other assets to the `public` folder. 537 | 538 | Note that we normally encourage you to `import` assets in JavaScript files instead. 539 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 540 | This mechanism provides a number of benefits: 541 | 542 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 543 | * Missing files cause compilation errors instead of 404 errors for your users. 544 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 545 | 546 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 547 | 548 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 549 | 550 | Inside `index.html`, you can use it like this: 551 | 552 | ```html 553 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 554 | ``` 555 | 556 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 557 | 558 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 559 | 560 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 561 | 562 | ```js 563 | render() { 564 | // Note: this is an escape hatch and should be used sparingly! 565 | // Normally we recommend using `import` for getting asset URLs 566 | // as described in “Adding Images and Fonts” above this section. 567 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 568 | } 569 | ``` 570 | 571 | Keep in mind the downsides of this approach: 572 | 573 | * None of the files in `public` folder get post-processed or minified. 574 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 575 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 576 | 577 | ### When to Use the `public` Folder 578 | 579 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 580 | The `public` folder is useful as a workaround for a number of less common cases: 581 | 582 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 583 | * You have thousands of images and need to dynamically reference their paths. 584 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 585 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 586 | 587 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 588 | 589 | ## Using Global Variables 590 | 591 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 592 | 593 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 594 | 595 | ```js 596 | const $ = window.$; 597 | ``` 598 | 599 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 600 | 601 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 602 | 603 | ## Adding Bootstrap 604 | 605 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 606 | 607 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 608 | 609 | ```sh 610 | npm install --save react-bootstrap bootstrap@3 611 | ``` 612 | 613 | Alternatively you may use `yarn`: 614 | 615 | ```sh 616 | yarn add react-bootstrap bootstrap@3 617 | ``` 618 | 619 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 620 | 621 | ```js 622 | import 'bootstrap/dist/css/bootstrap.css'; 623 | import 'bootstrap/dist/css/bootstrap-theme.css'; 624 | // Put any other imports below so that CSS from your 625 | // components takes precedence over default styles. 626 | ``` 627 | 628 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 629 | 630 | ```js 631 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 632 | ``` 633 | 634 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 635 | 636 | ### Using a Custom Theme 637 | 638 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 639 | We suggest the following approach: 640 | 641 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 642 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 643 | * Install your own theme npm package as a dependency of your app. 644 | 645 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 646 | 647 | ## Adding Flow 648 | 649 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 650 | 651 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 652 | 653 | To add Flow to a Create React App project, follow these steps: 654 | 655 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 656 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 657 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 658 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 659 | 660 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 661 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 662 | In the future we plan to integrate it into Create React App even more closely. 663 | 664 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 665 | 666 | ## Adding Custom Environment Variables 667 | 668 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 669 | 670 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 671 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 672 | `REACT_APP_`. 673 | 674 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 675 | 676 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 677 | 678 | These environment variables will be defined for you on `process.env`. For example, having an environment 679 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 680 | 681 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 682 | 683 | These environment variables can be useful for displaying information conditionally based on where the project is 684 | deployed or consuming sensitive data that lives outside of version control. 685 | 686 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 687 | in the environment inside a `<form>`: 688 | 689 | ```jsx 690 | render() { 691 | return ( 692 | <div> 693 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 694 | <form> 695 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 696 | </form> 697 | </div> 698 | ); 699 | } 700 | ``` 701 | 702 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 703 | 704 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 705 | 706 | ```html 707 | <div> 708 | <small>You are running this application in <b>development</b> mode.</small> 709 | <form> 710 | <input type="hidden" value="abcdef" /> 711 | </form> 712 | </div> 713 | ``` 714 | 715 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 716 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 717 | a `.env` file. Both of these ways are described in the next few sections. 718 | 719 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 720 | 721 | ```js 722 | if (process.env.NODE_ENV !== 'production') { 723 | analytics.disable(); 724 | } 725 | ``` 726 | 727 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 728 | 729 | ### Referencing Environment Variables in the HTML 730 | 731 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 732 | 733 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 734 | 735 | ```html 736 | <title>%REACT_APP_WEBSITE_NAME% 737 | ``` 738 | 739 | Note that the caveats from the above section apply: 740 | 741 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 742 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 743 | 744 | ### Adding Temporary Environment Variables In Your Shell 745 | 746 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 747 | life of the shell session. 748 | 749 | #### Windows (cmd.exe) 750 | 751 | ```cmd 752 | set REACT_APP_SECRET_CODE=abcdef&&npm start 753 | ``` 754 | 755 | (Note: the lack of whitespace is intentional.) 756 | 757 | #### Linux, macOS (Bash) 758 | 759 | ```bash 760 | REACT_APP_SECRET_CODE=abcdef npm start 761 | ``` 762 | 763 | ### Adding Development Environment Variables In `.env` 764 | 765 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 766 | 767 | To define permanent environment variables, create a file called `.env` in the root of your project: 768 | 769 | ``` 770 | REACT_APP_SECRET_CODE=abcdef 771 | ``` 772 | 773 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 774 | 775 | #### What other `.env` files are can be used? 776 | 777 | >Note: this feature is **available with `react-scripts@1.0.0` and higher**. 778 | 779 | * `.env`: Default. 780 | * `.env.local`: Local overrides. **This file is loaded for all environments except test.** 781 | * `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 782 | * `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 783 | 784 | Files on the left have more priority than files on the right: 785 | 786 | * `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 787 | * `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 788 | * `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 789 | 790 | These variables will act as the defaults if the machine does not explicitly set them.
791 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 792 | 793 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 794 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 795 | 796 | ## Can I Use Decorators? 797 | 798 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
799 | Create React App doesn’t support decorator syntax at the moment because: 800 | 801 | * It is an experimental proposal and is subject to change. 802 | * The current specification version is not officially supported by Babel. 803 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 804 | 805 | However in many cases you can rewrite decorator-based code without decorators just as fine.
806 | Please refer to these two threads for reference: 807 | 808 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 809 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 810 | 811 | Create React App will add decorator support when the specification advances to a stable stage. 812 | 813 | ## Integrating with an API Backend 814 | 815 | These tutorials will help you to integrate your app with an API backend running on another port, 816 | using `fetch()` to access it. 817 | 818 | ### Node 819 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 820 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 821 | 822 | ### Ruby on Rails 823 | 824 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 825 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 826 | 827 | ## Proxying API Requests in Development 828 | 829 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 830 | 831 | People often serve the front-end React app from the same host and port as their backend implementation.
832 | For example, a production setup might look like this after the app is deployed: 833 | 834 | ``` 835 | / - static server returns index.html with React app 836 | /todos - static server returns index.html with React app 837 | /api/todos - server handles any /api/* requests using the backend implementation 838 | ``` 839 | 840 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 841 | 842 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 843 | 844 | ```js 845 | "proxy": "http://localhost:4000", 846 | ``` 847 | 848 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 849 | 850 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 851 | 852 | ``` 853 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 854 | ``` 855 | 856 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 857 | 858 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
859 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 860 | 861 | * [Configure the proxy yourself](#configuring-the-proxy-manually) 862 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 863 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 864 | 865 | ### "Invalid Host Header" Errors After Configuring Proxy 866 | 867 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 868 | 869 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 870 | 871 | >Invalid Host header 872 | 873 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 874 | 875 | ``` 876 | HOST=mypublicdevhost.com 877 | ``` 878 | 879 | If you restart the development server now and load the app from the specified host, it should work. 880 | 881 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 882 | 883 | ``` 884 | # NOTE: THIS IS DANGEROUS! 885 | # It exposes your machine to attacks from the websites you visit. 886 | DANGEROUSLY_DISABLE_HOST_CHECK=true 887 | ``` 888 | 889 | We don’t recommend this approach. 890 | 891 | ### Configuring the Proxy Manually 892 | 893 | >Note: this feature is available with `react-scripts@1.0.0` and higher. 894 | 895 | If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
896 | You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. 897 | ```js 898 | { 899 | // ... 900 | "proxy": { 901 | "/api": { 902 | "target": "", 903 | "ws": true 904 | // ... 905 | } 906 | } 907 | // ... 908 | } 909 | ``` 910 | 911 | All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. 912 | 913 | If you need to specify multiple proxies, you may do so by specifying additional entries. 914 | You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. 915 | ```js 916 | { 917 | // ... 918 | "proxy": { 919 | // Matches any request starting with /api 920 | "/api": { 921 | "target": "", 922 | "ws": true 923 | // ... 924 | }, 925 | // Matches any request starting with /foo 926 | "/foo": { 927 | "target": "", 928 | "ssl": true, 929 | "pathRewrite": { 930 | "^/foo": "/foo/beta" 931 | } 932 | // ... 933 | }, 934 | // Matches /bar/abc.html but not /bar/sub/def.html 935 | "/bar/*.html": { 936 | "target": "", 937 | // ... 938 | }, 939 | // Matches /baz/abc.html and /baz/sub/def.html 940 | "/baz/**/*.html": { 941 | "target": "" 942 | // ... 943 | } 944 | } 945 | // ... 946 | } 947 | ``` 948 | 949 | ### Configuring a WebSocket Proxy 950 | 951 | When setting up a WebSocket proxy, there are a some extra considerations to be aware of. 952 | 953 | If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). 954 | 955 | There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). 956 | 957 | Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). 958 | 959 | Either way, you can proxy WebSocket requests manually in `package.json`: 960 | 961 | ```js 962 | { 963 | // ... 964 | "proxy": { 965 | "/socket": { 966 | // Your compatible WebSocket server 967 | "target": "ws://", 968 | // Tell http-proxy-middleware that this is a WebSocket proxy. 969 | // Also allows you to proxy WebSocket requests without an additional HTTP request 970 | // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade 971 | "ws": true 972 | // ... 973 | } 974 | } 975 | // ... 976 | } 977 | ``` 978 | 979 | ## Using HTTPS in Development 980 | 981 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 982 | 983 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 984 | 985 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 986 | 987 | #### Windows (cmd.exe) 988 | 989 | ```cmd 990 | set HTTPS=true&&npm start 991 | ``` 992 | 993 | (Note: the lack of whitespace is intentional.) 994 | 995 | #### Linux, macOS (Bash) 996 | 997 | ```bash 998 | HTTPS=true npm start 999 | ``` 1000 | 1001 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1002 | 1003 | ## Generating Dynamic `` Tags on the Server 1004 | 1005 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1006 | 1007 | ```html 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | ``` 1014 | 1015 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 1016 | 1017 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 1018 | 1019 | ## Pre-Rendering into Static HTML Files 1020 | 1021 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 1022 | 1023 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1024 | 1025 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1026 | 1027 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1028 | 1029 | ## Injecting Data from the Server into the Page 1030 | 1031 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1032 | 1033 | ```js 1034 | 1035 | 1036 | 1037 | 1040 | ``` 1041 | 1042 | 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.** 1043 | 1044 | ## Running Tests 1045 | 1046 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1047 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 1048 | 1049 | 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. 1050 | 1051 | 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. 1052 | 1053 | 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. 1054 | 1055 | 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. 1056 | 1057 | ### Filename Conventions 1058 | 1059 | Jest will look for test files with any of the following popular naming conventions: 1060 | 1061 | * Files with `.js` suffix in `__tests__` folders. 1062 | * Files with `.test.js` suffix. 1063 | * Files with `.spec.js` suffix. 1064 | 1065 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1066 | 1067 | 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. 1068 | 1069 | ### Command Line Interface 1070 | 1071 | 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. 1072 | 1073 | 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: 1074 | 1075 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1076 | 1077 | ### Version Control Integration 1078 | 1079 | 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. 1080 | 1081 | 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. 1082 | 1083 | 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. 1084 | 1085 | ### Writing Tests 1086 | 1087 | 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. 1088 | 1089 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1090 | 1091 | ```js 1092 | import sum from './sum'; 1093 | 1094 | it('sums numbers', () => { 1095 | expect(sum(1, 2)).toEqual(3); 1096 | expect(sum(2, 2)).toEqual(4); 1097 | }); 1098 | ``` 1099 | 1100 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1101 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. 1102 | 1103 | ### Testing Components 1104 | 1105 | 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. 1106 | 1107 | 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: 1108 | 1109 | ```js 1110 | import React from 'react'; 1111 | import ReactDOM from 'react-dom'; 1112 | import App from './App'; 1113 | 1114 | it('renders without crashing', () => { 1115 | const div = document.createElement('div'); 1116 | ReactDOM.render(, div); 1117 | }); 1118 | ``` 1119 | 1120 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. 1121 | 1122 | 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. 1123 | 1124 | 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: 1125 | 1126 | ```sh 1127 | npm install --save enzyme react-test-renderer 1128 | ``` 1129 | 1130 | Alternatively you may use `yarn`: 1131 | 1132 | ```sh 1133 | yarn add enzyme react-test-renderer 1134 | ``` 1135 | 1136 | You can write a smoke test with it too: 1137 | 1138 | ```js 1139 | import React from 'react'; 1140 | import { shallow } from 'enzyme'; 1141 | import App from './App'; 1142 | 1143 | it('renders without crashing', () => { 1144 | shallow(); 1145 | }); 1146 | ``` 1147 | 1148 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `