Learn to Create your Own React Starter Kit with ES6 support and more
Introduction to react starter kit.
Hello friends today I ‘am back with brand new tutorial. I am going to teach you how to setup your own react starter kit that support es6 and many more like redux, flux, etc. Don’t have any knowledge about how to create react starter kit or how backend works. Don’t worry I am here to help you. Before start you must know what I’am going to cover in this tutorial and how.
Want to download and setup reactjs starter kit instead of creating one. Click here
Reactjs Project Basic structure
For development I am going to use webpack-dev-sever with it’s full feature set that can help you to develop react application more easily. When deploying, your code is compiled, minimized and optimized using webpack. By default express server is automatically starts, when code compilation completed else you can setup your own separate server.
First of all for beginners who are not familiar with react above description about project structure may look like greek. I am sure you may get understanding about everything at the end of this tutorial.
Folder Structure for our react starter kit
Below shows the basic folder structure for our react project. All your react code goes inside src folder and project configurations are in config folder. Purpose of every folders and files will be described during this tutorial.
- config // Contain Project configurations
- config.js
- public
- index.html
- server
- webpack.dev.js //webpack configurations for development server
- server_dev.js //Webpack-dev-server
- webpack.prod.js //Webpack configurations for express server
- server_prod.js //Express server
- src //All your react codes goes in this folder
- entry.js //Entry point to your react application
- .babelrc
Step 01: Installing Required Modules
1.1: Installing node on your computer
a. Windows:- https://nodejs.org/en
b. Mac:- https://nodejs.org/en
c. Linux:-
sudo apt-get install curl
curl --silent --location https://deb.nodesource.com/setup_5.x | sudo bash -
sudo apt-get install nodejs
1.2: Installing Required packages for react starter kit
npm init
npm i --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0 express webpack webpack-dev-server
npm i --save path react react-dom
Step 02: Add project configurations
2.1: Add Project local configurations
Here only main configurations are added, like server port which run your react stater kit run.
File: /config/config.js
exports.SERVER_PORT = 3000;
2.2: Setup Webpack configurations for development environment.
Setting some useful features given by webpack to ease the development of reactjs web applications.
open /webpack.dev.js and add following code to it.
var path = require('path');
module.exports = {
devtool: 'source-map', //for development
entry: {
app: ["./src/entry.js"]
},
output: {
path: path.resolve(__dirname,"..", "public"),
filename: "bundle.js"
},
module: {
loaders: [
{
exclude: /node_modules/,
loaders: ['babel'],
test: /\.js$/,
}
]
},
};
What does above code do?. It will set entry point .js file for your react application. Why a single entry point. If you want you can add multiple entry points. Ref: https://webpack.github.io/docs/multiple-entry-points.html . Normally React applications has single entry point and all other related codes are linked to that file. All your related codes in different files are combined to a single js file containing all used libraries like react, react-dom, jQuery, etc. Here it is created in public folder and file name is bundle.js. Just need to add final compiled js (bundle.js) to html file. We are using babel to convert special syntaxes used here like ES6, JSX. It will be described later in this tutorial.
2.3: Setup Webpack configurations for production environment.
Add following code to /server/webpack.prod.js
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: {
app: ["./src/entry.js"]
},
output: {
path: path.resolve(__dirname,"..", "public"),
filename: "bundle.js"
},
module: {
loaders: [
{
exclude: /node_modules/,
loaders: ['babel'],
test: /\.js$/,
}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
minimize: true
}),
new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000}),
new webpack.optimize.LimitChunkCountPlugin({maxChunks: 15}),
new webpack.optimize.DedupePlugin()
]
};
Same as webpack.dev.js additional configurations are used to minimize and optimize the final compiled js. By default react is in development mode. No need to set that. When in production we need to change it’s environment. That’s why there is configuration like this.
"process.env": {
NODE_ENV: JSON.stringify("production")
}
all other extra lines are used to optimize final js. Read more https://webpack.github.io/docs/list-of-plugins.html
Step 03: Enabling React, JSX,ES6 support through babel.
Since we are using React, JSX, ES6 we need a method to handle those syntax. So we are using babel to convert those syntax to standard JavaScript so that it will work on almost all browsers that support JavaScript. Although we add babel loader to webpack, babel presets (syntax converters) are not working. For that we need to configure babel to use React,JSX and ES6. For that I’m using .babelrc file to define presets. By default babel will look for .babelrc file for it’s configurations.
.babelrc
{
"passPerPreset": true,
"presets": [
"react",
"es2015",
"stage-0"
]
}
Step 04: Creating Required Servers.
We are configuring 2 servers our react starter kit. One server is optimized for development and other is optimized for production.
4.1: Setup react development server using webpack-dev-server.
We are using two severs webpack-dev-server and express server. For development we are using webpack-dev-server. So I’am going to tell you how to configure webpack-dev-server for development.
/server/server_dev.js
var webpack = require("webpack")
var path = require("path");
var dev_server = require("webpack-dev-server")
var webpack_config = require("./webpack.dev.js")
var config = require("../config/config.js")
webpack_config.entry.app.unshift("webpack-dev-server/client?http://localhost:"+config.SERVER_PORT+"/");
var compiler = webpack(webpack_config);
var server =new dev_server(compiler, {
contentBase: path.resolve(__dirname,"..", "public"),
stats: {colors: true},
noInfo: true,
inline: true,
hot:false
})
server.listen(config.SERVER_PORT, "localhost", function(){
console.info("==> 🌎 Dev Server Listening on port %s. Open up http://localhost:%s/ in your browser. For inline mode server open up http://localhost:%s/webpack-dev-server/index.html", config.SERVER_PORT, config.SERVER_PORT, config.SERVER_PORT)
});
What we have done above is simple. We just add webpack configuration file and setup it’s compiler. Next created a instance of webpack-dev-server and add the created compiler to it. unshift function is called to link webpack-dev-server with front end in order to reload page on change. To stop automatic page reload change webpack hot to true. example: “hot:true”.
4.2: Setup Production Server using ExpressJs.
For this I’am using webpack and express server. Using webpack your react code is compiled and compress for production use. Then using express.js express server was setup to use that final compiled .js file.
/server/server_prod.js
var express = require("express")
var path = require("path");
var config = require("../config/config.js")
//Initialize server instance
var Server = new express();
//setting server routing
Server.get("/", function(req, res) {
res.sendFile(path.resolve(__dirname,"..", "public", "index.html"))
})
//Add Server Public Folder. Same location used for webpack-dev Server
Server.use(express.static(path.resolve(__dirname,"..", "public")));
Server.listen(config.SERVER_PORT, function(error) {
if (error) {
console.error(error)
} else {
console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", config.SERVER_PORT, config.SERVER_PORT)
}
})
Step 05: Create index.html file
This file is accessed by both servers. Public folder at root level is made public by both servers in order to access it publicly. If you want to add CSS, JS or other static assets you can place them inside public folder. Bootstrap and jQuery is added by me as an examples. You can refer that to add other assets or libraries that you need.
/public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title> React starter kit </title>
<link href="/css/bootstrap.min.css" type="text/css"/>
</head>
<body>
<div id="root" > </div>
<script src="/js/jQuery-2.2.4.js" type="text/javascript"></script>
<script src="/js/bootstrap.min.js" type="text/javascript"></script>
<script src="bundle.js" type="text/javascript"></script>
</body>
</html>
Step 06: Run Application in Development Mode.
Open your terminal/cmd and run following code.
npm i
npm start
Open your browser and run
localhost:3000 to run your application. Open browser console to view compilation status
To run application in inline mode
localhost:3000/webpack-dev-server/index.html
Step 07: Run React Application in Production mode.
npm i
npm run build
Step 08: Download react starter kit.
Download form GitHub
Direct download source code.
Help: Using the terminal go to download folder where you can see package.json file. From there enter below commands to run the application and then using browser go to http://localhost:3000 to see working react application.
npm i
npm start