Building a React Application with Webpack: A Comprehensive Guide

0

 Hello Everyone! Today, we are going to setup a sample project using latest version of react and webpack.

As everyone knows react as a powerful component based framework which allows building front-end in efficient manner. React framework is so versatile that you can build almost any kind of application for.e.g Single Page Apps (SPA), Mobile apps, Server side rendering applications etc.

So, let's get started!

I am using node v18.15.0 to run my code. By the time you start implementing this, it may be different but the essence of code is same.

React project

Note: we are not using the default react create project tooling. Instead I will be setting it up from scratch.

Setting up the Project:

  • Create a new directory for your project and navigate into it using your preferred command-line interface. 
  • Initialize a new Node.js project by running npm init and follow the prompts. 
  • Next, install the necessary dependencies by executing the command:
npm install react react-dom

Installing Webpack:

Webpack is a powerful module bundler that allows you to bundle and transform various assets such as JavaScript, CSS, and images. 
Install Webpack as a development dependency using the below command 
npm install webpack webpack-cli --save-dev

Configuring Webpack:

Create a new file in the root directory of your project called webpack.config.js. This file will hold the configuration for Webpack. 
Below is a basic configuration that you can start with:
  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
  module.exports = {
     entry: './src/index.js',
     output: {
        path: path.join(__dirname, '/dist'),
        filename: 'bundle.js'
     },
     devServer: {
        port: 8080
     },
     module: {
        rules: [
           {
              test: /\.jsx?$/,
              exclude: /node_modules/,
              loader: 'babel-loader',
           },
           {
              test: /\.css$/,
              use: [ 'style-loader', 'css-loader' ]
          }
        ]
     },
     plugins:[
         new HtmlWebpackPlugin({
              template: path.join(__dirname,'/src/index.html')
         }) 
     ]
  }
  
This configuration specifies the entry point for your application (./src/index.js), the output directory (dist), and the filename for the bundled JavaScript (bundle.js). It also includes rules for handling JavaScript and CSS files.

Babel for JavaScript Transpilation:

As React code often uses modern JavaScript features, it's essential to transpile it into compatible code for all browsers. 
Install Babel and its required plugins and presets by running below command: 
npm install @babel/core @babel/preset-env @babel/preset-react babel-loader --save-dev

Next, create a .babelrc file in the root directory of your project and add the following configuration:
{"presets":["@babel/preset-env", "@babel/preset-react"]}

Creating a React Component:

Create a new directory called `src` in the root of your project. Inside the src directory, create a file called index.js. This file will serve as the entry point for your React application. You can start by adding a basic React component to get things going. We are going to create a new counter component which will add or subtract counter by 1 and display it on screen. It can also reset the counter to 0. To achieve this we are going to use state hook from react hooks. 

If you want to learn more about React Hook please check the built-in rect hooks

Counter.js
  import React, { useEffect } from "react";
  import { useState } from "react";

  export function Counter() {
      const [count, setCount] = useState(0);

      function handleAddOne() {
        setCount(count + 1);
      }

      function handleMinusOne() {
        setCount(count - 1);
      }

      function handleReset() {
        setCount(0);
      }

      return (
        <div>
          <h1>Using state from react</h1>
          <h2>Count: {count}</h2>
          <button onClick={handleAddOne}>+1</button>
          <button onClick={handleMinusOne}>-1</button>
          <button onClick={handleReset}>Reset</button>
        </div>
      );
  }

index.js:

  import React from "react";
  import ReactDOM from "react-dom/client";
  import { Counter } from "./playground/counter";
    
   const root = ReactDOM.createRoot(document.getElementById("root"));
   root.render(<Counter />); 
    

index.html:

<!DOCTYPE html>
<html lang = "en">
   <head>
    <meta charset = "UTF-8">
    <title>React Web</title>
   </head>

<body>         <div id = "root"></div>         <script src = 'bundle.js'></script>    </body> </html>

Running the Application:

In your package.json file, add the following scripts:

  "scripts": {
    "start": "webpack serve --mode development --open --hot",
    "build": "webpack --mode production"
  }
Now, when you run npm start in your terminal, Webpack will compile your code and open it in your default browser. Any changes you make to your code will trigger an automatic reload. For a production build, you can run npm build which will generate a dist folder in your project with production level code.
 [wranto@PC counter-react-app-webpack]$ npm start
  > counter-react-app-webpack@1.0.0 start
  > webpack serve --mode development --open --hot

<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:8080/
<i> [webpack-dev-server] Content not from webpack is served from '/Users/wranto/workspace/react/counter-react-app-webpack/public' directory
<i> [webpack-dev-middleware] wait until bundle finished: /
asset bundle.js 1.39 MiB [emitted] (name: main)
asset index.html 257 bytes [emitted]
  
finally you should be able to see the below output in your browser window:
React-with-webpack


Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*

Cookies Consent

This website uses cookies to offer you a better Browsing Experience. By using our website, You agree to the use of Cookies

Privacy Policy