React project building with Webpack

Last Updated: October 9, 2021

This is the most popular way of building reactjs applications.

In this tutorial, we will see how we can build the React application with Webpack.
You will need the following two files to get started

This is the folder structure for this tutorial

\webpack-demo
  \src
    index.js
  \dist
    \assets
    index.html

index.html file in dist folder in your working directory and it will have the following code

  
    
    
  
    
 
  

index.js file is located at src folder and compiled versions of it will be placed at dist\assests\index.min.js

So your index.js file will have following contents

ReactDOM.render(

Hello World New

, document.getElementById(‘root’) )

You can run following command to make the package.json file

npm init

This will create the package.json file

You will need Babel-CLI to compile JS code

npm install --save babel-cli

Now you can install the presets using following command in your terminal

npm install --save-dev babel-preset-latest babel-preset-react babel-preset-stage-0

I will create the webpack.config.js file in the root directory of the project and it should have the following contents

var webpack=require('webpack');

module.exports={
  entry:"./src/index.js",
  output:{
    path:__dirname + "/dist/assets",
    filename:"index.min.js"
  },
  devServer:{
    inline:true,
    contentBase:"./dist",
    port:3000
  },
  module:{
    loaders:[
      {
        test:/\.js$/,
        exclude:/(node_modules)/,
        loader:'babel-loader',
        query:{
          presets:['latest','react','stage-0']
        }
      }
    ]
  }
}

Now you can install the Webpack

npm install webpack --save-dev

New you can install the Babel-Loader

 npm install babel-loader --save-dev

Next, you can install the Webpack Dev Server

npm install webpack-dev-server --save-dev

Your final package.json file will be like this

{
  "name": "static-babel",
  "version": "1.0.0",
  "description": "Static babel compile",
  "main": "index.js",
  "scripts": {
     "start": "./node_modules/.bin/webpack-dev-server"
  },
  "author": "Mark Taylor",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0"
  },
  "devDependencies": {
    "babel-loader": "^7.1.2",
    "babel-preset-latest": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.9.7"
  }
}

Now you can run the following npm command to transpile the js code and start the web server

npm start

Now you can see the web page at http://localhost:3000/