How to Configure Webpack 5 with React from Scratch (2026 Guide)

Modern React development often relies on streamlined build tools like Vite. However, mastering Webpack remains essential for developers handling enterprise legacy applications or requiring deep, fine-grained control over their production bundles.

In this guide, you will learn how to configure **Webpack 5** with **React 19** and **Babel** from scratch, setting up a professional development environment with hot reloading, linting foundation, and optimized production builds.


Prerequisites

Before proceeding, ensure you have the following installed on your machine:

  • Node.js (LTS or latest stable version)
  • A terminal environment (VS Code terminal, Git Bash, terminal)
  • Basic knowledge of command-line operations

Step 1: Project Initialization

Create a new project folder and generate a default package.json file:

# Create directory
mkdir webpack-react-lab
cd webpack-react-lab

# Initialize package.json
npm init -y

Step 2: Install React and Webpack

First, install the runtime dependencies (React) and the core build tools (Webpack):

# Install runtime dependencies (React)
npm install react react-dom

# Install development dependencies (Webpack core)
npm install webpack webpack-cli webpack-dev-server --save-dev

Step 3: Setup Babel (JavaScript Transpiler)

Since browsers cannot execute JSX or modern ES6+ JavaScript directly, we need **Babel** to compile our code back to compatible ES5/ES6.

npm install babel-loader @babel/core @babel/preset-env @babel/preset-react --save-dev

Create a new file in the root directory named babel.config.json and paste this configuration:

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

(Note: `runtime: automatic` enables the modern JSX transform, eliminating the need to `import React` in every file.)


Step 4: Install Essential Loaders and Plugins

We need additional loaders to handle CSS, styles, and plugins to generate the main HTML entry point.

# For CSS handling
npm install css-loader style-loader --save-dev

# To generate the main index.html file
npm install html-webpack-plugin --save-dev

Step 5: Create Project Files

We must set up the source directories and the essential entry files before configuring Webpack.

# Create source folder
mkdir src
mkdir src/components

# Create entry files
touch src/index.js
touch src/App.js
touch src/index.html

Add content to src/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Webpack 5 React lab</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

Add content to src/App.js:

export default function App() {
  return (
    <div style={{ padding: '20px', fontFamily: 'sans-serif' }}>
      <h1>Hello Webpack <span style={{ color: '#61dafb' }}>React 19!</span></h1>
      <p>Built from scratch without create-react-app.</p>
    </div>
  );
}

Add React 19 rendering to src/index.js:

import { createRoot } from 'react-dom/client';
import App from './App';

// Find the root div
const container = document.getElementById('root');

// Create a root for the application
const root = createRoot(container);

// Render the application to the root
root.render(<App />);

Step 6: Configure Webpack (webpack.config.js)

Create the main configuration file in the root directory: webpack.config.js. This file tells Webpack how to handle different file types, plugins, and server options.

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

module.exports = {
  // 1. Set development mode
  mode: 'development',

  // 2. Main JavaScript entry point
  entry: './src/index.js',

  // 3. Define output bundle
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    clean: true, // Auto-clean 'dist' on each build
  },

  // 4. Optimization: Configure the DevServer
  devServer: {
    static: './dist',
    port: 3000,
    open: true, // Auto-open browser
    hot: true, // Enable Hot Module Replacement
    compress: true, // Enable gzip compression
    historyApiFallback: true, // Support for React Router
  },

  // 5. Module Rules: Handle different file types
  module: {
    rules: [
      // Rules for compiling JSX/JavaScript with Babel
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
      // Rules for handling CSS
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      // Modern Asset Modules for images/fonts (Webpack 5+)
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
    ],
  },

  // 6. Define extensions for cleaner imports
  resolve: {
    extensions: ['.js', '.jsx'],
  },

  // 7. Configure Plugins
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html', // Inject bundle into this template
    }),
  ],
};

Step 7: Update scripts in `package.json`

We need to add shortcuts to start the development server and build the production bundle easily.

Open package.json and find the "scripts" section. Update it to look like this:

"scripts": {
  "start": "webpack serve",
  "build": "webpack --mode production",
  "test": "echo \"Error: no test specified\" && exit 1"
},

Step 8: Run and Build the Application

Run Development Server:

npm start

This will start the server on `http://localhost:3000`. Your browser should auto-open, showing "Hello Webpack React 19!". Make a change in `App.js` and see it update instantly.

Build Production Bundle:

npm run build

Webpack will compile the code, optimize the assets, and place the output files in the newly generated `dist` directory. This is the production-ready code you deploy.


Conclusion

Congratulations! You have successfully configured Webpack 5 from scratch for a modern React 19 application. Although tools like Vite are the default recommendation for new projects, understanding how Webpack manages dependency resolution, asset compilation, and HMR equips you with a powerful understanding of how React apps function under the hood.

Happy Coding! 🚀

Comments

Popular posts from this blog

React Performance Optimization: Profiling, Reconciliation, and Rendering Boundaries

Mastering React Icons: Installation, Customization, and Best Practices (2026 Guide)