FOR DEVELOPERS

How to Use Webpack With React

How to Use Webpack With React

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

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

npm install react react-dom

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

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"
  }
}

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

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>

App.js

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

index.js

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

import App from "./App";

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

root.render(<App />);

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

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"], } }, }, ], }, };

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"
  }
}

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>

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.

Author

  • How to Use Webpack With React

    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.

Frequently Asked Questions

It depends on the project but webpack gives complete control over the project whereas create-react-app prevents default configuration.

By default, webpack bundles the jsx and js files into one file. This may decrease the overall performance of the application, so the best solution is code splitting the bundled js into chunks and loaded when needed in the browser. Some of the plugins that do this is the html-webpack plugin.

Webpack is a js build tools that combine loaders including babel and plugins that bundles the Javascript while babel is a js compiler to compile js and jsx files.

Yes you can use React without webpack, you can use its alternatives like using React with Vite and Parcel that performs the same function as webpack.

There are other JS build tools apart from webpack like Vite, Parcel, and Esbuild that are powerful and can be integrated and used in a React project.

No React is independent of a module bundler, it’s the developer who chooses one but when initializing a React project using Create React App (CRA) webpack is also included by default.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.