Back to Top

How to use Webpack with React JS

Updated 17 May 2024

Webpack is a powerful tool for bundling the javascript application. It is free and open source, you can bundle the entire javascript application into a single file.

Primarily web pack is made only for the javascript application but it can also transform the frontend assets such as HTML, CSS, and Images with the help of corresponding loaders.

Advantages of Using Webpack

There are several advantages of using a webpack, some of them are as follows:-

  • Dependency Management:- It automatically handles your dependencies, reducing the version conflicts risk and making it easy to manage project structure.
  • Faster Deployment:- After bundling the project, we have fewer files for deployment which makes the deployment process faster.
  • It can transpile newer javascript features to ensure compatibility with older environments.

Setting up the React Project with Webpack

Now, we are going to set up a react project from scratch with webpack configuration (requirement: node and npm must be installed in the system)

Step 1: Create a new folder and run the following command in terminal:-

Start your headless eCommerce
now.
Find out More
npm init -y
# OR
yarn init -y

It will generate the package.json file with some entry

{
  "name": "test-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Step 2: Now, install Webpack and Babel

npm i webpack webpack-cli webpack-dev-server --save-dev
# OR
yarn i webpack webpack-cli webpack-dev-server --save-dev

Step 3: Install the core Babel package and its presets

npm i @babel/core @babel/preset-env @babel/preset-react
# OR
yarn i @babel/core @babel/preset-env @babel/preset-react

Step 4: Install the HTML Webpack plugin for automatically creating an HTML file that serves the webpack-generated javascript file.

npm i html-webpack-plugin --save-dev
# OR
yarn i html-webpack-plugin --save-dev

Step 5: Install the loaders (this can be modified as per the project requirements)

npm i babel-loader style-loader css-loader --save-dev
# OR
yarn i babel-loader style-loader css-loader --save-dev

Step 6: Now, For setting up the react, Install the react and react-dom

npm i react react-dom --save
# OR
yarn i react react-dom --save

Step 7: Now, create a src folder and add the following files.

// index.html 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
// App.js

import React from 'react';

const App = () => {
    return (
        <div>Welcome to React!</div>
    );
}

export default App;
// index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(<App />, document.getElementById('root'));

Step 8: Now, make a webpack.config.js file in the root directory of the project and add the following code

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    "entry": "./src/index.js",
    "output": {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: "babel-loader"
            },
            {
                test: /\.css$/,
                use: [
                    {
                        loader: "style-loader"
                    },
                    {
                        loader: "css-loader"
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./src/index.html"
        })
    ]
}

Step 9: Create a .babelrc file in the root directory of the project and add the following code

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

Step 10: Now, at last, modify the script section of the package.json file and add

"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --config webpack.config.js"

Step 11: Now, run the project via the ‘npm start’ or ‘yarn start’ command. This will start the webpack development server. Here, the open and hot options open the react app in the browser and enable hot reloading respectively.

Step 12: Run the build command via ‘npm run build’ or ‘yarn run build’ to get the dist folder that contains the normal bundled JS and HTML file.

Extract the dist folder and run it as static HTML, CSS and JS project via direct clicking on index.html file or running from any server such as live server of vs-code.

Transform the node js server into a Single file

Now, we are going to transform our node js server into a single file using Webpack.

Step 1: Download the ‘webpack’ and ‘webpack-cli’ in your project

npm install --save-dev webpack webpack-cli
# OR
yarn install --save-dev webpack webpack-cli

Step 2: After that add the build script inside package.json file of your project

"scripts": {
  "build": "webpack --config webpack.config.cjs",
}

Step 3: Make webpack.config.cjs file inside the root directory of the project and write the following code

const path = require('path');
module.exports = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, './bundle'),
        filename: 'server.js',
    },
    resolve: {
        extensions: ['.js']
    },
    target: 'node',
    stats: 'errors-only'
}

Step 4: Run the ‘npm run build’ or ‘yarn build’ via the terminal. It will generate a static folder namely ‘bundle’.

Step 5: Open the bundle folder in the terminal now, you can see that the bundle folder contains two files one is server.js (output: filename) and another one is server.js.LICENSE.txt.

For running the server, run the below command that will Initialise the package.json file inside the bundle folder.

npm init 
# OR 
yarn init
// now, node js ask following questions

package name: (bundle)
version: (1.0.0) 
description:
entry point: (server.js)
test command:
git repository: 
keywords: 
author: 
license: (ISC)

and 

Is this OK? (yes)

// package.json file is generated. Now, you can run the server.js file

Step 6: Run the single-page server file by typing the following command

node server.js 
# OR 
yarn server.js

Step 7: Now, you can see that the server.js file is working. You can also put the env file inside the bundle folder to provide the required environment variables to the server.

Note: For the best practice before bundling the application move the .env file and entry file of the node js server into the root directory.

Step 8: Enjoy the bundling.

Conclusion

Webpack simplifies the process of managing dependencies and bundling multiple files into one, improving the overall performance of the application.

Additionally, developers can optimize their code for better loading times and enhanced user experience.

For more information visit the official site of Webpack.

Start your Headless Development with Webkul.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home