├── .flowconfig
├── tests
└── index.test.js
├── .gitattributes
├── .gitignore
├── example-app
├── src
│ ├── index.css
│ ├── index.js
│ ├── App.test.js
│ ├── App.css
│ ├── App.js
│ └── logo.svg
├── public
│ ├── favicon.ico
│ └── index.html
├── .gitignore
├── __tests__
│ └── App.test.js
├── package.json
└── README.md
├── .travis.yml
├── .editorconfig
├── generators
├── bootstrap
│ ├── templates
│ │ └── component.template.js
│ └── index.js
├── initialState.js
├── app
│ └── index.js
├── testIndex
│ ├── templates
│ │ └── index.template.js
│ └── index.js
└── test
│ ├── templates
│ └── index.template.js
│ └── index.js
├── LICENSE
├── package.json
├── helpers
└── actionNameCreator.js
└── README.md
/.flowconfig:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/tests/index.test.js:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | coverage
3 |
--------------------------------------------------------------------------------
/example-app/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: sans-serif;
5 | }
6 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - v6
4 | - v5
5 | - v4
6 | - '0.12'
7 | - '0.10'
8 |
--------------------------------------------------------------------------------
/example-app/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rakannimer/generator-react-jest-tests/HEAD/example-app/public/favicon.ico
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 2
6 | charset = utf-8
7 | trim_trailing_whitespace = true
8 | insert_final_newline = true
9 |
10 | [*.md]
11 | trim_trailing_whitespace = false
12 |
--------------------------------------------------------------------------------
/example-app/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 | import './index.css';
5 |
6 | ReactDOM.render(
7 | ,
8 | document.getElementById('root')
9 | );
10 |
--------------------------------------------------------------------------------
/example-app/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render(, div);
8 | });
9 |
--------------------------------------------------------------------------------
/example-app/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 |
6 | # testing
7 | /coverage
8 |
9 | # production
10 | /build
11 |
12 | # misc
13 | .DS_Store
14 | .env
15 | npm-debug.log*
16 | yarn-debug.log*
17 | yarn-error.log*
18 | .vscode
19 |
--------------------------------------------------------------------------------
/generators/bootstrap/templates/component.template.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | class <%=COMPONENT_NAME%> extends React.Component {
4 | constructor(props){
5 | super(props);
6 | }
7 | render() {
8 | return (
9 |
10 | <%=COMPONENT_NAME%>
11 |
12 | );
13 | }
14 | };
15 | export default <%=COMPONENT_NAME%>;
16 |
--------------------------------------------------------------------------------
/example-app/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 80px;
8 | }
9 |
10 | .App-header {
11 | background-color: #222;
12 | height: 150px;
13 | padding: 20px;
14 | color: white;
15 | }
16 |
17 | .App-intro {
18 | font-size: large;
19 | }
20 |
21 | @keyframes App-logo-spin {
22 | from { transform: rotate(0deg); }
23 | to { transform: rotate(360deg); }
24 | }
25 |
--------------------------------------------------------------------------------
/generators/initialState.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "REDUCERS_PATH": "./src/reducers/",
3 | "SAGAS_PATH": "./src/sagas/",
4 | "ACTION_NAMES_PATH":"./src/actions/",
5 | "MIDDLEWARES_PATH":"./src/middlewares/",
6 | "CONTAINERS_PATH": "./src/containers/",
7 | "COMPONENTS_PATH": "./src/components/",
8 | "STORE_PATH" : "./src/store/",
9 | "ACTION_NAMES_PATH": "./src/actionNames/",
10 | "CONSTANTS_PATH": "./src/constants/",
11 | 'TESTS_PATH': './src/__tests__/'
12 | };
13 |
--------------------------------------------------------------------------------
/example-app/__tests__/App.test.js:
--------------------------------------------------------------------------------
1 | // Auto-generated do not edit
2 |
3 | /* eslint-disable import/no-extraneous-dependencies */
4 | /* eslint-disable no-undef */
5 | import React from 'react';
6 | import renderer from 'react-test-renderer';
7 | import App from '../src/App';
8 |
9 | describe('App test', () => {
10 | it('App should match snapshot', () => {
11 | const component = renderer.create();
12 | const tree = component.toJSON();
13 | expect(tree).toMatchSnapshot();
14 | });
15 | });
16 |
--------------------------------------------------------------------------------
/generators/app/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | var yeoman = require('yeoman-generator');
3 | var chalk = require('chalk');
4 | var yosay = require('yosay');
5 | // var actionNameCreator = require("../../helpers/actionNameCreator");
6 |
7 | module.exports = yeoman.Base.extend({
8 | prompting: function () {
9 | // Have Yeoman greet the user.
10 | this.log(yosay(
11 | `Welcome to the ${chalk.red(`react-redux-saga-cli`)} generator!
12 | The following commands are supported :
13 | yo react-redux-saga-cli:test
14 | `
15 | ));
16 | }
17 | });
18 |
--------------------------------------------------------------------------------
/example-app/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import logo from './logo.svg';
3 | import './App.css';
4 |
5 | class App extends Component {
6 | render() {
7 | return (
8 |
9 |
10 |

11 |
Welcome to React
12 |
13 |
14 | To get started, edit src/App.js and save to reload.
15 |
16 |
17 | );
18 | }
19 | }
20 |
21 | export default App;
22 |
--------------------------------------------------------------------------------
/generators/testIndex/templates/index.template.js:
--------------------------------------------------------------------------------
1 | // Auto-generated do not edit
2 |
3 |
4 | /* eslint-disable import/no-extraneous-dependencies */
5 | /* eslint-disable no-undef */
6 | import React from 'react';
7 | import renderer from 'react-test-renderer';
8 | import <%= filename %> from '../components/<%=filename%>';
9 |
10 | <%= JSON.stringify(componentProps, 2, 2) />
11 |
12 | describe('<%=filename%> test', () => {
13 | it('<%= filename %> should match snapshot', () => {
14 | const component = renderer.create(<<%= filename%> />);
15 | const tree = component.toJSON();
16 | expect(tree).toMatchSnapshot();
17 | });
18 | });
19 |
--------------------------------------------------------------------------------
/example-app/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "example-app",
3 | "version": "0.1.0",
4 | "private": true,
5 | "devDependencies": {
6 | "react-scripts": "^3.0.0"
7 | },
8 | "dependencies": {
9 | "react": "^15.4.2",
10 | "react-dom": "^15.4.2"
11 | },
12 | "scripts": {
13 | "start": "react-scripts start",
14 | "build": "react-scripts build",
15 | "test": "react-scripts test --env=jsdom",
16 | "eject": "react-scripts eject"
17 | },
18 | "browserslist": {
19 | "production": [
20 | ">0.2%",
21 | "not dead",
22 | "not op_mini all"
23 | ],
24 | "development": [
25 | "last 1 chrome version",
26 | "last 1 firefox version",
27 | "last 1 safari version"
28 | ]
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/generators/bootstrap/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | var yeoman = require('yeoman-generator');
3 | var chalk = require('chalk');
4 | var yosay = require('yosay');
5 | var state = require('../initialState');
6 | var fs = require('fs');
7 | var path = require('path');
8 |
9 | const mkdirp = require('mkdirp-promise/lib/node4')
10 |
11 | module.exports = yeoman.Base.extend({
12 |
13 | initializing: function(){
14 | console.log(yosay("Let's bootstrap this app !"));
15 | },
16 | prompting: function () {
17 | //console.log(yosay("Let's bootstrap this app !"));
18 | },
19 |
20 | writing: function () {
21 | mkdirp('./components')
22 | mkdirp('./containers');
23 | mkdirp('./reducers');
24 | mkdirp('./sagas');
25 | mkdirp('./middlewares');
26 | mkdirp('./store');
27 | },
28 | end : function () {
29 |
30 | },
31 | });
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 RakanNimer (https://www.github.com/RakanNimer)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/example-app/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
16 | React App
17 |
18 |
19 |
20 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/generators/test/templates/index.template.js:
--------------------------------------------------------------------------------
1 |
2 | // Auto-generated do not edit
3 |
4 |
5 | /* eslint-disable import/no-extraneous-dependencies */
6 | /* eslint-disable no-undef */
7 | import React from 'react';
8 | import renderer from 'react-test-renderer';
9 | import <%- filename %> from '<%-relativeFilePath%>';
10 |
11 |
12 | describe('<%-filename%> test', () => {
13 | it('<%- filename %> should match snapshot', () => {
14 | const component = renderer.create(<<%- filename%>
15 | <%- componentProps.map(componentMeta => {
16 | return ""+componentMeta.propName+"={"+
17 | // (
18 | // (componentMeta.propType === 'string')
19 | // ?
20 | // "'"
21 | // :
22 | // ''
23 | // )
24 | // +
25 | (
26 | (componentMeta.propType === 'shape' || componentMeta.propType === 'string') ?
27 | JSON.stringify(componentMeta.propDefaultValue,null,1)
28 | :
29 | componentMeta.propDefaultValue
30 | )
31 | // +
32 | // (
33 | // (componentMeta.propType === 'string')
34 | // ?
35 | // "'"
36 | // :
37 | // ''
38 | // )
39 | +
40 | "}"
41 | } ).join(' ') %> />);
42 | const tree = component.toJSON();
43 | expect(tree).toMatchSnapshot();
44 | });
45 | });
46 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "generator-react-jest-tests",
3 | "version": "0.3.1",
4 | "description": "react jest tests generator",
5 | "homepage": "https://www.github.com/rakannimer/generator-react-jest-tests",
6 | "author": {
7 | "name": "RakanNimer",
8 | "email": "rakannimer@gmail.com",
9 | "url": "https://www.github.com/rakannimer/"
10 | },
11 | "files": [
12 | "generators"
13 | ],
14 | "main": "generators/app/index.js",
15 | "keywords": [
16 | "react",
17 | "jest",
18 | "test",
19 | "tests",
20 | "snapshot",
21 | "cli",
22 | "generator",
23 | "yeoman-generator"
24 | ],
25 | "dependencies": {
26 | "chalk": "^1.0.0",
27 | "debug": "^2.6.1",
28 | "fs-readdir-recursive": "^1.0.0",
29 | "path": "^0.12.7",
30 | "prettier": "^0.20.0",
31 | "react-component-metadata": "^3.1.0",
32 | "react-docgen": "^2.10.0",
33 | "yeoman-generator": "^2.0.3",
34 | "yosay": "^1.0.0"
35 | },
36 | "devDependencies": {
37 | "eslint": "^4.18.2",
38 | "eslint-config-xo-space": "^0.14.0",
39 | "gulp": "^3.9.0",
40 | "gulp-eslint": "^2.0.0",
41 | "gulp-exclude-gitignore": "^1.0.0",
42 | "gulp-istanbul": "^1.0.0",
43 | "gulp-line-ending-corrector": "^1.0.1",
44 | "gulp-mocha": "^2.0.0",
45 | "gulp-nsp": "^2.1.0",
46 | "gulp-plumber": "^1.0.0",
47 | "mkdirp-promise": "^3.0.1",
48 | "yeoman-assert": "^2.0.0",
49 | "yeoman-test": "^1.0.0"
50 | },
51 | "eslintConfig": {
52 | "extends": "xo-space",
53 | "env": {
54 | "mocha": true
55 | }
56 | },
57 | "repository": "https://www.github.com/rakannimer/generator-react-jest-tests",
58 | "scripts": {},
59 | "license": "MIT"
60 | }
61 |
--------------------------------------------------------------------------------
/helpers/actionNameCreator.js:
--------------------------------------------------------------------------------
1 | var state = require('../generators/initialState');
2 | var actionNameCreator = {
3 | readActionsFromUserland: function(){
4 | try {
5 | var file = require("html-wiring").readFileAsString(state.CONSTANTS_PATH+"ACTION_NAMES.json");
6 | var parsedActions = JSON.parse(file);
7 | return parsedActions;
8 | }
9 | catch(err){
10 | console.warn("Error reading constants : ", err);
11 | return {};
12 | }
13 | },
14 | actionsToPrettyString: function(actionNames){
15 | var actionNamesArray = Object.keys(actionNames).map(function(actionName){return actionName});
16 | var actionNamesString = actionNamesArray.reduce(function(prev, current){
17 | return prev+" \n"+"****** "+current+" ";
18 | },"")
19 | return actionNamesString;
20 | },
21 |
22 | addActions: function(newActions){
23 | var oldActions = this.readActionsFromUserland();
24 | var updatedActions = {};
25 |
26 | Object.keys(oldActions).forEach(function (actionName){
27 | updatedActions[actionName] = actionName;
28 | })
29 |
30 | newActions.forEach(function(newActionName){
31 | updatedActions[newActionName] = newActionName;
32 | })
33 | return updatedActions;
34 | },
35 | writeActions: function(generator, actions){
36 | var file = require("html-wiring").writeFileFromString( JSON.stringify(actions, 2, 2), state.CONSTANTS_PATH+"ACTION_NAMES.json");
37 |
38 | },
39 | logActions: function(){
40 | var actionNames = this.readActionsFromUserland(this);
41 | var actionNamesString = this.actionsToPrettyString(actionNames);
42 | console.log(
43 | "I found the following actions: "+actionNamesString
44 | );
45 |
46 | }
47 | };
48 |
49 | module.exports = actionNameCreator;
50 |
--------------------------------------------------------------------------------
/example-app/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/generators/testIndex/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | var yeoman = require('yeoman-generator');
3 | var chalk = require('chalk');
4 | var yosay = require('yosay');
5 | var state = require('../initialState');
6 | var fs = require('fs');
7 | var path = require('path');
8 | var reactDocs = require('react-docgen');
9 | var Parser = require("simple-text-parser");
10 | var parser = new Parser();
11 |
12 | const makeParser = (filepath) => {
13 | let foundProps = [];
14 |
15 | }
16 |
17 | const addParserRule = (filePath) => {
18 | let foundProps = []
19 | parser.addRule(/(props(.\w+))/ig, (tag) => {
20 | let propName = tag.split('.');
21 | propName.splice(0,1);
22 | if ( foundProps.indexOf(propName.join('.')) !== -1 ){
23 | return;
24 | }
25 | foundProps.push(propName.join('.'));
26 | });
27 | }
28 |
29 |
30 | let foundProps = {};
31 | const extractProps = (filePath) => {
32 | const fileString = fs.readFileSync(filePath, 'utf8');
33 | let matchedProps = fileString.match(/props(.[a-zA-Z]+)([^(\(|}| |\[|;|,)])+/g);
34 | if (matchedProps === null){
35 | return [];
36 | }
37 | matchedProps = matchedProps.map((prop) => {
38 | let newProp = prop;
39 | let parsedProp = newProp.split('.');
40 | parsedProp.shift();
41 | parsedProp.join('.');
42 | return parsedProp.join('.');
43 | });
44 | return matchedProps.filter(function(item, pos, self) {
45 | return self.indexOf(item) === pos;
46 | })
47 | }
48 |
49 | module.exports = yeoman.Base.extend({
50 | prompting: function () {
51 | this.log(yosay('Creating components index.js'));
52 | },
53 |
54 | writing: function () {
55 | var components;
56 | try {
57 | components = fs.readdirSync(state.COMPONENTS_PATH);
58 | var indexFileIndex = components.indexOf('index.js');
59 | if (indexFileIndex > -1){
60 | components.splice(indexFileIndex, 1);
61 | }
62 | var indexFileIndex = components.indexOf('.DS_Store');
63 | if (indexFileIndex > -1){
64 | components.splice(indexFileIndex, 1);
65 | }
66 |
67 | }
68 | catch(err){
69 | console.log("ERROR while reading from directory ", err);
70 | components = [];
71 | }
72 | const a = (path)=>{
73 | // console.log("EXTRACTING PROPS FROM ", path);
74 | extractProps(path);
75 | }
76 | let propsArray = components.map((component) => {
77 | return extractProps(state.COMPONENTS_PATH+component);
78 | });
79 | console.log(propsArray);
80 | this.fs.copyTpl(
81 | this.templatePath('index.template.js'),
82 | this.destinationPath(state.TESTS_PATH+'index.test.js'),
83 | { components: components, props: propsArray }
84 | );
85 |
86 | }
87 | });
88 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React Jest tests yeoman generator
2 |
3 | ## What's that ?
4 |
5 | This is a [Yeoman](http://yeoman.io) generator used to generate Jest snapshot tests by parsing react components defaultProps and propTypes.
6 | The tests are linted with [prettier](https://github.com/prettier/prettier) and outputted to the current directory's ```__tests__``` folder.
7 |
8 | ## Why ?
9 |
10 | Writing smoke tests for well-defined components can (and should) easily be offloaded to software. This is a solution I use across projects to bootstrap tests.
11 |
12 |
13 | ## Installation
14 |
15 | First, install [Yeoman](http://yeoman.io) and generator-react-jest-tests using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)).
16 |
17 | ```bash
18 | npm install -g yo
19 | npm install -g generator-react-jest-tests
20 | ```
21 |
22 |
23 | ## Commands
24 |
25 | Suppose you have the following file structure
26 | ```
27 | - app/
28 | - components/
29 | - MyComp.js
30 | - MaybeSome.css
31 | - AndA.png
32 | - storesOrUtils/
33 | - someFile.js
34 | ```
35 |
36 | Silent :
37 |
38 | ```
39 | yo react-jest-tests:test
40 | ```
41 | Verbose :
42 |
43 | ```
44 | DEBUG=generator-react-jest-tests* yo react-jest-tests:test
45 | ```
46 |
47 | ```
48 | _-----_
49 | | |
50 | |--(o)--| ╭──────────────────────────╮
51 | `---------´ │ Let's create tests │
52 | ( _´U`_ ) ╰──────────────────────────╯
53 | /___A___\ /
54 | | ~ |
55 | __'.___.'__
56 | ´ ` |° ´ Y `
57 |
58 | ? Give me the path to components please ! (./src/components/)
59 | ```
60 |
61 | Give the path to your folder or ```cd``` to it and put ```./``` as path
62 |
63 | Will output :
64 | ```
65 | create __tests__/MyComp.js
66 | ```
67 |
68 | and result in :
69 |
70 | ```
71 | - app/
72 | - components/
73 | - __tests__
74 | - MyComp.test.js
75 | - MyComp.js
76 | - MaybeSome.css
77 | - AndA.png
78 | - storesOrUtils/
79 | - someFile.js
80 | ```
81 | ```
82 | - app/
83 | - components/
84 | - __tests__
85 | - MyComp.test.js
86 | - MyComp.js
87 | - MaybeSome.css
88 | - AndA.png
89 | - storesOrUtils/
90 | - someFile.js
91 | ```
92 |
93 | Run jest to make sure everything is working as expected.
94 |
95 | Any error can be resolved by specifying defaultProps, if no defaultProps are passed propTypes will be parsed to try to generate fake data. Fake Data generation from propTypes is a WIP.
96 |
97 | To write seamless and predictable tests add defaultProps to your component definitions.
98 |
99 | ## Conflicts
100 |
101 | By default it won't overwrite anything without asking you first.
102 |
103 | ## License
104 |
105 | MIT © [RakanNimer](https://www.github.com/RakanNimer)
106 |
--------------------------------------------------------------------------------
/generators/test/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | var Generator = require('yeoman-generator');
3 | var yosay = require('yosay');
4 | var fs = require('fs');
5 | var path = require('path');
6 | var read = require('fs-readdir-recursive');
7 | var reactDocs = require('react-docgen');
8 | var debug = require('debug');
9 | const prettier = require('prettier');
10 |
11 | const log = debug('generator-react-jest-tests:log');
12 | const error = debug('generator-react-jest-tests:error');
13 |
14 | const _extends = Object.assign || function (target) {
15 | for (var i = 1; i < arguments.length; i++) {
16 | var source = arguments[i];
17 | for (var key in source) {
18 | if (Object.prototype.hasOwnProperty.call(source, key)) {
19 | target[key] = source[key];
20 | }
21 | }
22 | }
23 | return target;
24 | };
25 |
26 | const filenameFromPath = filePath => {
27 | log('filenameFromPath ', filePath);
28 | const filePathNoExtension = filePath.split('.js');
29 | const filePathNoExtensionArray = filePathNoExtension[0].split('/');
30 | const filename = filePathNoExtensionArray[filePathNoExtensionArray.length - 1];
31 | return filename;
32 | };
33 |
34 | const generateFakeProp = ({propName, name, value, raw}) => {
35 | log('generateFakeProp ', {propName, name, value, raw});
36 | const isShape = typeof (value) === 'object';
37 | if (isShape) {
38 | const fakeShape = {};
39 | Object.keys(value).forEach(shapeChildName => {
40 | const fakeProp = generateFakeProp({propName, name: shapeChildName, value: value[shapeChildName].name});
41 | const fakePropName = fakeProp.name;
42 | const fakePropValue = fakeProp.value;
43 | fakeShape[fakePropName] = fakePropValue;
44 | });
45 | return {propName, name, value: fakeShape};
46 | }
47 | switch (value) {
48 | case 'number':
49 | return {name, value: 42};
50 | case 'string':
51 | return {name, value: "'defaultString'"};
52 | case 'bool':
53 | return {name, value: true};
54 | case 'array':
55 | return {name, value: []};
56 | default:
57 | switch (name) {
58 | case 'func':
59 | return {name, value: '() => {}'};
60 | case 'number':
61 | return {name, value: 42};
62 | case 'string':
63 | return {name, value: "'defaultString'"};
64 | case 'bool':
65 | return {name, value: true};
66 | case 'array':
67 | return {name, value: []};
68 | default:
69 | switch (raw) {
70 | case 'PropTypes.func':
71 | return {name, value: '() => {}'};
72 | case 'PropTypes.number':
73 | return {name, value: 42};
74 | case 'PropTypes.string':
75 | return {name, value: "'defaultString'"};
76 | case 'PropTypes.bool':
77 | return {name, value: true};
78 | case 'PropTypes.array':
79 | return {name, value: []};
80 | default:
81 | return {name, value: 'unrecognizedType ' + name + ' ' + value + ', consider reporting error to react-jest-test-generator.'};
82 | }
83 | }
84 |
85 | }
86 | // return {name, value};
87 | };
88 |
89 | const extractDefaultProps = (filePath, currentFilePath) => {
90 | log('extractDefaultProps ', {filePath, currentFilePath});
91 | const filename = filenameFromPath(filePath); // filePathNoExtensionArray[filePathNoExtensionArray.length - 1];
92 | const fileString = fs.readFileSync(filePath, 'utf8');
93 | try {
94 | var componentInfo = reactDocs.parse(fileString);
95 | } catch (err) {
96 | console.log(filePath, 'is not a React Component, ');
97 | throw new Error(err);
98 | }
99 | const componentProps = [];
100 | const componentHasProps = componentInfo.props ? componentInfo.props : false;
101 | if (!componentHasProps) {
102 | error('No props found in ', filename, ' at ', filePath);
103 | return {filePath, componentProps, filename, currentFilePath};
104 | }
105 |
106 | const propNames = Object.keys(componentInfo.props);
107 | for (let i = 0; i < propNames.length; i += 1) {
108 | const propName = propNames[i];
109 | let propType;
110 | if (componentInfo.props[propName].type) {
111 | propType = componentInfo.props[propName].type.name;
112 | } else {
113 | error('propType not set for ' + propName + ' in ' + filename + ' at ' + currentFilePath + ' consider setting it in propTypes');
114 | propType = 'string';
115 | }
116 | let propDefaultValue;
117 | const hasDefaultvalue = componentInfo.props[propName].defaultValue ? componentInfo.props[propName].defaultValue : false;
118 | if (hasDefaultvalue) {
119 | //eslint-disable-next-line
120 | error(componentInfo.props[propName].defaultValue);
121 | propDefaultValue = componentInfo.props[propName].defaultValue.value; // ? componentInfo.props[currentProp] : '-1';
122 | error({propName, propType, propDefaultValue});
123 | } else {
124 | error('defaultProps value not set for ' + propName + ' in ' + filename + ' at ' + currentFilePath + ' consider setting it in defaultProps');
125 | error('!!! Will try to generate fake data this might cause unexpected results !!!');
126 | const {type, required, description} = componentInfo.props[propName];
127 | const {name, value, raw} = type;
128 | if (required) {
129 | const fakeProp = generateFakeProp({propName, name, value, raw});
130 | propDefaultValue = fakeProp.value;
131 | log('Generated ', fakeProp, 'returning it as ', {propName, propType, propDefaultValue, currentFilePath});
132 | }
133 | }
134 | componentProps.push({propName, propType, propDefaultValue, currentFilePath});
135 | // process.exit();
136 | }
137 | return {filePath, componentProps, componentInfo, filename, currentFilePath};
138 | };
139 |
140 | module.exports = class extends Generator {
141 | constructor(args, opts) {
142 | super(args, opts);
143 | this.option('prettify', {
144 | descr: 'If true, lint code with prettify',
145 | alias: 'pr',
146 | type: Boolean,
147 | default: false,
148 | hide: false
149 | });
150 | this.option('template', {
151 | desc: 'Custom template to use for tests',
152 | alias: 't',
153 | type: String,
154 | default: '',
155 | hide: false
156 | });
157 | }
158 | prompting() {
159 | if (this.options.template.length) {
160 | this.log(`Received custom template of: ${this.options.template}`);
161 | }
162 | this.log(yosay('Let\'s create tests'));
163 | var prompts = [
164 | {
165 | type: 'input',
166 | name: 'COMPONENTS_PATH',
167 | message: 'Give me the path to components please !',
168 | default: './src/components/'
169 | }
170 | ];
171 | if (this.options.isNested) {
172 | this.props = this.options.props;
173 | } else {
174 | return this.prompt(prompts).then(function (props) {
175 | this.props = props;
176 | }.bind(this));
177 | }
178 | }
179 | writing() {
180 | const filePaths = read(this.props.COMPONENTS_PATH).filter(filename => filename.endsWith('.js'));
181 | if (filePaths.length === 0) {
182 | const noJsMessage = 'Did not find any .js files';
183 | console.log(noJsMessage);
184 | error(noJsMessage);
185 | }
186 | const metadata = [];
187 | for (let i = 0; i < filePaths.length; i += 1) {
188 | const currentFilePath = filePaths[i];
189 | const completeFilePath = this.props.COMPONENTS_PATH + currentFilePath;
190 | try {
191 | const componentInfo = extractDefaultProps(completeFilePath, currentFilePath);
192 | metadata.push(componentInfo);
193 | } catch (err) {
194 | error('Couldnt extractDefaultProps from ' + currentFilePath + ' at ' + completeFilePath);
195 | error(err);
196 | // process.exit();
197 | }
198 | }
199 | for (let i = 0; i < metadata.length; i += 1) {
200 | const compMetaData = metadata[i];
201 | const testPath = path.resolve(compMetaData.filePath, path.join('..', '__tests__', compMetaData.filename + '.test.js'));
202 | const templatePath = this.options.template.length ? path.join(this.sourceRoot('.'), this.options.template) : 'index.template.js';
203 | this.fs.copyTpl(
204 | this.templatePath(templatePath),
205 | this.destinationPath(testPath),
206 | _extends({}, compMetaData, {relativeFilePath: path.join('..', compMetaData.filename)})
207 | );
208 | try {
209 | const generatedTestCode = this.fs.read(testPath);
210 | const formattedTestCode = this.options.prettify ? prettier.format(generatedTestCode, {
211 | singleQuote: true,
212 | trailingComma: 'all'
213 | }) : generatedTestCode;
214 | this.fs.write(testPath, formattedTestCode);
215 | } catch (err) {
216 | error('Couldnt lint generated code :( from ' + compMetaData);
217 | }
218 | }
219 | }
220 | };
221 |
--------------------------------------------------------------------------------
/example-app/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
2 |
3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
5 |
6 | ## Table of Contents
7 |
8 | - [Updating to New Releases](#updating-to-new-releases)
9 | - [Sending Feedback](#sending-feedback)
10 | - [Folder Structure](#folder-structure)
11 | - [Available Scripts](#available-scripts)
12 | - [npm start](#npm-start)
13 | - [npm test](#npm-test)
14 | - [npm run build](#npm-run-build)
15 | - [npm run eject](#npm-run-eject)
16 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
17 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
18 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
19 | - [Debugging in the Editor](#debugging-in-the-editor)
20 | - [Changing the Page ``](#changing-the-page-title)
21 | - [Installing a Dependency](#installing-a-dependency)
22 | - [Importing a Component](#importing-a-component)
23 | - [Adding a Stylesheet](#adding-a-stylesheet)
24 | - [Post-Processing CSS](#post-processing-css)
25 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
26 | - [Adding Images and Fonts](#adding-images-and-fonts)
27 | - [Using the `public` Folder](#using-the-public-folder)
28 | - [Changing the HTML](#changing-the-html)
29 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
30 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
31 | - [Using Global Variables](#using-global-variables)
32 | - [Adding Bootstrap](#adding-bootstrap)
33 | - [Using a Custom Theme](#using-a-custom-theme)
34 | - [Adding Flow](#adding-flow)
35 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
36 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
37 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
38 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
39 | - [Can I Use Decorators?](#can-i-use-decorators)
40 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
41 | - [Node](#node)
42 | - [Ruby on Rails](#ruby-on-rails)
43 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
44 | - [Using HTTPS in Development](#using-https-in-development)
45 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
46 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
47 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
48 | - [Running Tests](#running-tests)
49 | - [Filename Conventions](#filename-conventions)
50 | - [Command Line Interface](#command-line-interface)
51 | - [Version Control Integration](#version-control-integration)
52 | - [Writing Tests](#writing-tests)
53 | - [Testing Components](#testing-components)
54 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
55 | - [Initializing Test Environment](#initializing-test-environment)
56 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
57 | - [Coverage Reporting](#coverage-reporting)
58 | - [Continuous Integration](#continuous-integration)
59 | - [Disabling jsdom](#disabling-jsdom)
60 | - [Snapshot Testing](#snapshot-testing)
61 | - [Editor Integration](#editor-integration)
62 | - [Developing Components in Isolation](#developing-components-in-isolation)
63 | - [Making a Progressive Web App](#making-a-progressive-web-app)
64 | - [Deployment](#deployment)
65 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
66 | - [Building for Relative Paths](#building-for-relative-paths)
67 | - [Azure](#azure)
68 | - [Firebase](#firebase)
69 | - [GitHub Pages](#github-pages)
70 | - [Heroku](#heroku)
71 | - [Modulus](#modulus)
72 | - [Netlify](#netlify)
73 | - [Now](#now)
74 | - [S3 and CloudFront](#s3-and-cloudfront)
75 | - [Surge](#surge)
76 | - [Advanced Configuration](#advanced-configuration)
77 | - [Troubleshooting](#troubleshooting)
78 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
79 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
80 | - [`npm run build` silently fails](#npm-run-build-silently-fails)
81 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
82 | - [Something Missing?](#something-missing)
83 |
84 | ## Updating to New Releases
85 |
86 | Create React App is divided into two packages:
87 |
88 | * `create-react-app` is a global command-line utility that you use to create new projects.
89 | * `react-scripts` is a development dependency in the generated projects (including this one).
90 |
91 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
92 |
93 | 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.
94 |
95 | 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.
96 |
97 | 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.
98 |
99 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
100 |
101 | ## Sending Feedback
102 |
103 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
104 |
105 | ## Folder Structure
106 |
107 | After creation, your project should look like this:
108 |
109 | ```
110 | my-app/
111 | README.md
112 | node_modules/
113 | package.json
114 | public/
115 | index.html
116 | favicon.ico
117 | src/
118 | App.css
119 | App.js
120 | App.test.js
121 | index.css
122 | index.js
123 | logo.svg
124 | ```
125 |
126 | For the project to build, **these files must exist with exact filenames**:
127 |
128 | * `public/index.html` is the page template;
129 | * `src/index.js` is the JavaScript entry point.
130 |
131 | You can delete or rename the other files.
132 |
133 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
134 | You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them.
135 |
136 | Only files inside `public` can be used from `public/index.html`.
137 | Read instructions below for using assets from JavaScript and HTML.
138 |
139 | You can, however, create more top-level directories.
140 | They will not be included in the production build so you can use them for things like documentation.
141 |
142 | ## Available Scripts
143 |
144 | In the project directory, you can run:
145 |
146 | ### `npm start`
147 |
148 | Runs the app in the development mode.
149 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
150 |
151 | The page will reload if you make edits.
152 | You will also see any lint errors in the console.
153 |
154 | ### `npm test`
155 |
156 | Launches the test runner in the interactive watch mode.
157 | See the section about [running tests](#running-tests) for more information.
158 |
159 | ### `npm run build`
160 |
161 | Builds the app for production to the `build` folder.
162 | It correctly bundles React in production mode and optimizes the build for the best performance.
163 |
164 | The build is minified and the filenames include the hashes.
165 | Your app is ready to be deployed!
166 |
167 | See the section about [deployment](#deployment) for more information.
168 |
169 | ### `npm run eject`
170 |
171 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
172 |
173 | 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.
174 |
175 | 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.
176 |
177 | 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.
178 |
179 | ## Supported Language Features and Polyfills
180 |
181 | This project supports a superset of the latest JavaScript standard.
182 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
183 |
184 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
185 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
186 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
187 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal).
188 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
189 |
190 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
191 |
192 | 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.
193 |
194 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
195 |
196 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
197 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
198 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
199 |
200 | 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.
201 |
202 | ## Syntax Highlighting in the Editor
203 |
204 | 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.
205 |
206 | ## Displaying Lint Output in the Editor
207 |
208 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
209 |
210 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
211 |
212 | 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.
213 |
214 | You would need to install an ESLint plugin for your editor first.
215 |
216 | >**A note for Atom `linter-eslint` users**
217 |
218 | >If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked:
219 |
220 | >
221 |
222 |
223 | >**For Visual Studio Code users**
224 |
225 | >VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line:
226 |
227 | >```js
228 | {
229 | // ...
230 | "extends": "react-app"
231 | }
232 | ```
233 |
234 | Then add this block to the `package.json` file of your project:
235 |
236 | ```js
237 | {
238 | // ...
239 | "eslintConfig": {
240 | "extends": "react-app"
241 | }
242 | }
243 | ```
244 |
245 | Finally, you will need to install some packages *globally*:
246 |
247 | ```sh
248 | npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@2.2.3 eslint-plugin-flowtype@2.21.0
249 | ```
250 |
251 | We recognize that this is suboptimal, but it is currently required due to the way we hide the ESLint dependency. The ESLint team is already [working on a solution to this](https://github.com/eslint/eslint/issues/3458) so this may become unnecessary in a couple of months.
252 |
253 | ## Debugging in the Editor
254 |
255 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.**
256 |
257 | Visual Studio Code supports live-editing and 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.
258 |
259 | 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.
260 |
261 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
262 |
263 | ```json
264 | {
265 | "version": "0.2.0",
266 | "configurations": [{
267 | "name": "Chrome",
268 | "type": "chrome",
269 | "request": "launch",
270 | "url": "http://localhost:3000",
271 | "webRoot": "${workspaceRoot}/src",
272 | "userDataDir": "${workspaceRoot}/.vscode/chrome",
273 | "sourceMapPathOverrides": {
274 | "webpack:///src/*": "${webRoot}/*"
275 | }
276 | }]
277 | }
278 | ```
279 |
280 | 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.
281 |
282 | ## Changing the Page ``
283 |
284 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
285 |
286 | 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.
287 |
288 | 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.
289 |
290 | 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).
291 |
292 | ## Installing a Dependency
293 |
294 | 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`:
295 |
296 | ```
297 | npm install --save
298 | ```
299 |
300 | ## Importing a Component
301 |
302 | This project setup supports ES6 modules thanks to Babel.
303 | 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.
304 |
305 | For example:
306 |
307 | ### `Button.js`
308 |
309 | ```js
310 | import React, { Component } from 'react';
311 |
312 | class Button extends Component {
313 | render() {
314 | // ...
315 | }
316 | }
317 |
318 | export default Button; // Don’t forget to use export default!
319 | ```
320 |
321 | ### `DangerButton.js`
322 |
323 |
324 | ```js
325 | import React, { Component } from 'react';
326 | import Button from './Button'; // Import a component from another file
327 |
328 | class DangerButton extends Component {
329 | render() {
330 | return ;
331 | }
332 | }
333 |
334 | export default DangerButton;
335 | ```
336 |
337 | 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.
338 |
339 | 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'`.
340 |
341 | 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.
342 |
343 | Learn more about ES6 modules:
344 |
345 | * [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)
346 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
347 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
348 |
349 | ## Adding a Stylesheet
350 |
351 | This project setup uses [Webpack](https://webpack.github.io/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
352 |
353 | ### `Button.css`
354 |
355 | ```css
356 | .Button {
357 | padding: 20px;
358 | }
359 | ```
360 |
361 | ### `Button.js`
362 |
363 | ```js
364 | import React, { Component } from 'react';
365 | import './Button.css'; // Tell Webpack that Button.js uses these styles
366 |
367 | class Button extends Component {
368 | render() {
369 | // You can use them as regular CSS styles
370 | return ;
371 | }
372 | }
373 | ```
374 |
375 | **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.
376 |
377 | 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.
378 |
379 | 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.
380 |
381 | ## Post-Processing CSS
382 |
383 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it.
384 |
385 | For example, this:
386 |
387 | ```css
388 | .App {
389 | display: flex;
390 | flex-direction: row;
391 | align-items: center;
392 | }
393 | ```
394 |
395 | becomes this:
396 |
397 | ```css
398 | .App {
399 | display: -webkit-box;
400 | display: -ms-flexbox;
401 | display: flex;
402 | -webkit-box-orient: horizontal;
403 | -webkit-box-direction: normal;
404 | -ms-flex-direction: row;
405 | flex-direction: row;
406 | -webkit-box-align: center;
407 | -ms-flex-align: center;
408 | align-items: center;
409 | }
410 | ```
411 |
412 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
413 |
414 | ## Adding a CSS Preprocessor (Sass, Less etc.)
415 |
416 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `` and `` components, we recommend creating a `