How to Use Webpack With React

4 min read

  • Languages, frameworks, tools, and trends

React is a JavaScript Library for building user interfaces. It simplifies web development by breaking the User Interface (UI) into small blocks known as components that can be reused across pages in the website. If you are familiar with React you might’ve heard the term create-react-app, create-react-app (CRA) is a command line interface that spins up a react project quickly by setting up everything under the hood and saves time for the developer to start developing any desired website. Still, under the hood, use of webpack with React is done to configure the output react project.

What is webpack?

According to the webpack official site, webpack is a static module bundler for modern JavaScript applications. Its primary purpose is to bundle JavaScript to use in the browser.
Webpack also has many features apart from bundling JavaScript code like hot reload replacement feature that removes the pain of having to refresh the browser for every new feature added to the codebase. There are other options for bundling JavaScript apart from webpack like Parcel, Vite, and Turbopack. In this article, we are going to see how to use and configure webpack from scratch in a React project.

Getting started

Create an empty directory and run the following command to initiate an npm project,

npm init -y
Bash

Install react and react-dom in the project with the following command

npm install react react-dom
Bash

Now we need to install Webpack and its dependencies for the project with the following command,

Npm i -D webpack webpack-dev-server webpack-cli
Bash

Now let’s see the use of each package we installed earlier:

  • react: This is the library for creating user interfaces where we’ll import most APIs from it like useState, useContext, and useEffect.
  • react-dom: This package provides Document Object Model (DOM) specific methods that can be used at the top level of your app and as an escape hatch to get outside the React model if you need to.

Next, open package.json and you should see something like this:

json
{
  "name": "webpack-blog",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {},
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.11.1"
  }
}
Plaintext

Now let’s see the use of the development dependencies as shown in the package.json file above.

  • webpack: This is the core library, a Javascript bundler that will be used in the project.
  • webpack-cli: According to their page, this library provides a flexible set of useful commands for developers to increase speed while6 setting up a custom webpack project.
  • webpack-dev-server: This will provide a live reloading feature so we don’t have to refresh the web page each time we make a change to the codebase, and it should be used in development only.

Project setup

The code base right now only consists of a package.json, package-lock.json, and a node_modules directory. It is not resembling the React project we are used to see when we initialize with Create React App. Now let’s add some files in the src folder that will be populated later to make it much more of a React project hence the project structure will be like:

|____src
|	I____App.js
|	I____index.css
|	I____index.html
|	I____index.js
|_____package-lock.json
|_____package.json
|_____webpack.config.js
HTML

Let’s start populating the files with some code, starting with index.html,

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to use Webpack with React</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>
HTML

App.js

js
export default function App() {
  return (
    <div>
      <h1>React App</h1>
    </div>
  );
}
JavaScript

index.js

js
import ReactDOM from "react-dom/client";

import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("app"));

root.render(<App />);
JavaScript

At this time even if you try to run the project it won’t work as we haven’t specified webpack configurations and utilized loaders.

What are loaders?

Loaders are an essential part of Webpack in a React project as they are responsible for parsing the JSX files and compiling complex JSX files to browser-understandable Javascript files. For this codebase, we will use the babel-loader to perform the task of loaders, install the library with the command below:

bash
npm install -D @babel/core @babel/preset-env @babel/preset-react babel-loader
Bash

The command above installs babel, babel-loader, and two presets.

Configuring webpack

Next, we have to instruct webpack to use babel for compiling JSX and other configurations for babel itself, the configuration is done in the webpack.config.js file as follows:

js
const path = require("path");

module.exports = {
  entry: "./src/index.js",
  output: { path: path.resolve(__dirname, "dist") },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options:{
            presets: ["@babel/preset-env", "@babel/preset-react"],
          }
        },
      },
    ],
  },
};
JavaScript

The above configuration makes use of the babel-loader wherever it finds files with js or jsx extension.

Starting the React app

Now we have to set up a build script in the package.json file for bundling the application:

{
  "name": "webpack-blog",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.20.12",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^9.1.2",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.11.1"
  }
}
JavaScript

We’ve added the build script and tested it by running npm run build and you will see a dist folder is created that contains a bundled main.js file that can be attached to the index.html file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>How to use Webpack with React</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="../dist/main.js"></script>
  </body>
</html>
HTML

Now open the browser and you will see the output is as it is defined in App.js

At this time the project is successfully using React and webpack.

Conclusion

Customizing webpack from scratch is really helpful for large apps and brings a good developer experience as it gives more control to the project. Give it a try and explore some more features and powers of webpack.

Now that you know how webpack can be integrated into React projects, it will be helpful to explore some other module bundlers before you choose one that fits your project needs.

How to Use Webpack With React

Author
Shabani Nassibu

Shanas is a software developer with 3 years of experience and a technical writer specialized in frontend development with tech stacks like Nextjs, React, Vue, Tailwind and backend development with Django, django rest framework. He is currently working as a freelancer but he is open to any remote job opportunities.

Share this post