React setup with webpack and babel 2020

In today post we are going to learn about how to setup a React app with webpack and babel from scratch. Webpack is a static module bundler for modern JavaScript applications.

When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

1. Setup new directory

Its always good to setup a new directory for your project. You can create a new directory for your project and then open a terminal on same location and type below command to initialize your app

npm init -y

2. Install Webpack and add build command

Webpack is a module bundler. Webpack can take care of bundling alongside a separate task runner. However, the line between bundler and task runner has become blurred thanks to community developed webpack plugins.

Sometimes these plugins are used to perform tasks that are usually done outside of webpack, such as cleaning the build directory or deploying the build.

npm i webpack webpack-cli --save-dev

Add below script in your package.json

"scripts": {
  "build": "webpack --mode production"
}

3. Add babel for transpiling

We prefer to use ES6 syntax with React. But older browser can’t understand new syntax. To overcome this issue we takeos help from babel.

Babel takes ES6 javascript code and compile it into ES5 code so that older browsers can understand it. This conversion is called transpiling.

The next big term is loader. The loaders are nothing but small plugin which helps webpack to make bundle. There is seprate loader for all functionality like file-loader, less-loader, babel-loader, html-loader, css-loader and so, on.

babel-loader is the webpack loader responsible for talking to Babel. Babel on the other hand must be configured to use presets.

Now babel also relies on two presets those are

  • babel preset env for compiling modern Javascript down to ES5
  • babel preset react for compiling JSX and other stuff down to Javascript
npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev

We need to create a new file in root of our project i.e .babelrc and put preset config in this file.

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

Now we need to add babel-loader in webpack.config.js file

module.exports = {
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        resolve: {
          extensions: ['.js', '.jsx'],
        },
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

4. Adding React and React-dom

Its time to add react and react-dom to our project.

npm i react react-dom --save

You can create a new index file in src directory now

import React from 'react';
import ReactDOM from 'react-dom';


const wrapper = document.getElementById('app');
// eslint-disable-next-line react/jsx-filename-extension
ReactDOM.render(<div>Working</div>, wrapper);

Now if you try to run npm run build you can see dist/main.js. You code is compiled by webpack now.

5. Add Html plugin for webpack

To display our React form we must tell webpack to produce an HTML page. The resulting bundle will be placed inside a <script> tag.

webpack needs two additional components for processing HTML: html-webpack-plugin and html-loader. Add the dependencies with:

npm i html-webpack-plugin html-loader --save-dev

After installing above packages you need to update your webpack.config.js file

const HtmlWebPackPlugin = require('html-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        resolve: {
          extensions: ['.js', '.jsx'],
        },
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /.html$/,
        use: [
          {
            loader: 'html-loader',
          },
        ],
      },
    ],
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: './src/index.html',
      filename: './index.html',
    }),
  ],
};

Now create index.html in src directory

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Webpack</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

Now again try npm run build command and you can see index.html file in dist directory now. You can open that html file and see what you are getting in your browser.

6. Adding webpack-dev-server

You don’t want to type npm run build every time you change a file. It takes only 3 lines of configuration to have a development server up and running.

Once configured webpack will launch your application inside a browser. Also, every time you save a file after a modification webpack dev server will refresh the browser’s window.

npm i webpack-dev-server --save-dev

Now update your package.json file again and add this start script

"scripts": {
  "start": "webpack-dev-server --open --mode development",
  "build": "webpack --mode production"
}

If you run npm start now you can see your react app on browser with hot reloading enable.

Full project is available on github for reference here.

I hope you have learned React setup with webpack and babel 2020.

Check our this article for setup React with Parceljs.

Categories: Reactjs