The Minimal React Project Setup using Webpack 2 and Babel

There are a good number of starter kits available for creating React projects. Starter kits are useful but most of them are black boxes, they improve the productivity once the developers have the understanding of how the stuff works.

The goal of this blog post is to explain how to create basic React project using Webpack 2 and Babel from scratch step by step.

Create project folder


mkdir react-basic-project
cd react-basic-project
npm init

Install React and React DOM packages


npm install --save react
npm install --save react-dom

Install Webpack 2 and Webpack Dev Server


npm install --save-dev webpack@2
npm install --save-dev webpack-dev-server@2

Install Babel Core and Babel Loader


npm install --save-dev babel-core
npm install --save-dev babel-loader

  • babel-core is the Babel compiler
  • babel-loader is the Webpack plugin for Babel

Install Babel presets for ES2015 and React


npm install --save-dev babel-preset-es2015
npm install --save-dev babel-preset-react

  • babel-preset-es2015 is the Babel preset for all ES2015 plugins
  • babel-preset-react is the Babel preset for all React plugins

We have all the required npm packages, let’s write some code. First, we need to create Babel configuration in .babelrc file to tell Babel how to transpile our ES2015 and JSX code.


touch .babelrc

Add the following configuration to .babelrc file.


{
  "presets": ["react", ["es2015", { "modules": false }]]
}

Lets create Webpack configuration file webpack.config.js.


touch webpack.config.js

Add the following configuration to webpack.config.js file.


module.exports = {
  entry: './src/app',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      }
    ]
  }
};

Here is the hello world React code.

src/helloworld.js


import React, { Component } from 'react';

class HelloWorld extends Component {
  render() {
    return (<h1>Hello, React World!</h1>); 
  } 
} 

export default HelloWorld;

src/app.js


import React from 'react';
import { render } from 'react-dom';

import HelloWorld from './helloworld';

render(<HelloWorld />, document.getElementById('app-root'));

index.html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>React Hello World</title>
</head>
<body>
  <div id="app-root"></div>
  <script src="bundle.js"></script>
</body>
</html>

You can find the sample code here.