First you need to install nodejs either from http://nodejs.org/ or using nvm
node version manager tool.
https://github.com/facebookincubator/create-react-app is a better way to scaffold react app, so give it a try
npm init
npm install react react-dom react-router --save
npm install redux react-redux --save
npm install webpack webpack-dev-server --save-dev
npm install babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-2 --save-dev
These steps will generate package.json
file, install and add dependencies and development dependencies into package.json file.
create a file named webpack.config.js
in a project root directory and copy below codes in it
var path = require('path');
var DIST_DIR = path.resolve(__dirname, 'dist');
var SRC_DIR = path.resolve(__dirname, 'src');
var config = {
entry: SRC_DIR + '/app/index.js',
output: {
path: DIST_DIR + '/app',
filename: 'bundle.js',
public_path: '/app/'
},
module: {
loaders: [{
test: /\.js?/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-2']
}
}]
}
};
module.exports = config;
Here we have told webpack, about our entrypoint
, output build folder to use when we run build command later and
bundle everything into /app/bundle.js
file. Also we setup babel preset loaders for all .js
files.
Your directory structure should look something like this:
react-app
|-- node_modules
|-- src
|-- app
|-- index.js
index.html
package.json
webpack.config.js
README.md
LICENSE.md
setup start
, build
and build:prod
commands in package.json
file as a scripts
object.
{
....
"scripts": {
"start": "npm run build",
"build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot",
"build:prod": "webpack -p && cp src/index.html dist/index.html",
}
....
}
src/app/index.js
import { createStore } from 'redux'
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
const store = createStore(counter);
store.subscribe(() =>
console.log(store.getState())
)
store.dispatch({ type: 'INCREMENT' }) // => 1
store.dispatch({ type: 'INCREMENT' }) // => 2
store.dispatch({ type: 'DECREMENT' }) // => 1
This is a sample redux
script grabbed from http://redux.js.org/
src/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React App</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
minimal html5 code snippit.
npm install
npm start
This command should generate dist/
directory with your index.html
file and app/bundle.js
file inside it
and start your development server in http://localhost:8080. Visit this url in your browser which should be blank,
but if you open developer console, you should see working
printed there.
Happy Coding!!