Create a React Web Application Using Webpack 5 Full Walkthrough

Amila Devin
12 min readMay 11, 2022

What is React?

React is a free and open-source front-end JavaScript library for building user interfaces based on UI components. It is maintained by Meta and a community of individual developers and companies.

How to Create a React App Easily?

We can create a React App environment easily using one command.

npx create-react-app <your app name>
create-react-app

What is Create React App?

Create React App is a command-line tool from Facebook that lets us build a React application without having to bother about settings and setup.

Why was Create React App Created?

The biggest benefit of using Create React App is that it requires less learning. Newcomers may find developing a React application overwhelming due to additional procedures such as transpiring code, packaging assets, and so on.

Create React App is pre-configured with a code transpiler and a module bundler, saving you time. In fact, one command using Create React App will set up all of the tools required to launch a React application.

How do we create a React App without the create-react-app command?

Only the React, ReactDOM, and Babel libraries are required to build a React application. For instance, we might just use the CDNs listed below.

Writing React code in this manner is good for small projects or testing, but for a production-level web application, we need set up a React environment. A JavaScript transpiler and a module bundler are part of the React ecosystem.

What is a Transpiler?

The newest version of JavaScript code, such as arrow functions and class syntax, is recommended by React. We need a transpiler because most browsers don’t grasp this new syntax.

A transpiler is a program that translates one type of code into another. A JavaScript transpiler is required to transform one type of JavaScript code to another type of JavaScript code. We specifically want a transpiler that translates ES5 and ES6 code into browser-friendly code.

JavaScript Transpiler

Babel

Babel is the JavaScript transpiler that we’ll be utilizing. Babel is a JavaScript transpiler that translates ECMAScript 2015+ code into previous and newer browser/environment backward compatible JavaScript versions.

how babel works

What is a Module Bundler?

A module bundler combines a collection of files of various categories, such as JavaScript scripts, pictures, and stylesheets, into a smaller set of files. React uses module bundlers to assist us to handle dependency connections, such as loading modules in the right sequence.

Webpack

Webpack bundler works

Webpack will be used as a module bundler. Webpack combines files of various sorts, such as JavaScript and front-end asset files (HTML, CSS, pictures, and so on), into a single package. Webpack also produces a dependency graph, which allows you to load modules in the proper order. We could use Browserify or Gulp as alternatives, but webpack is the most extensively used React module bundler.

Getting Started

Creating our Project Folders

Create a folder to hold our React application and then step inside it.

mkdir create-react-app-from-webpack-5

cd create-react-app-from-webpack-5

Initializing the Project

To initialize the project by running npm init. This will create a package.json file to keep track of our dependencies, development dependencies, metadata, and more.

npm init -y

-y argument which is a shortcut for providing all the defaults when initializing an npm project.

Initializing the Project

Installing Dependencies

npm install react react-dom
  • React: React is just a library
  • ReactDOM: ReactDOM is a package that acts as a glue between React and the DOM.

The document object model is abbreviated as DOM. A HTML page is treated by the DOM as a tree structure, with each node representing a component of the content. When a web page is loaded, the browser constructs a document object model (DOM) for it.

ReactDOM provides DOM-specific functions that may be used at a web application’s top level.

Installing Dependencies

Installing Dev Dependencies

We install these package as a dev dependency because it isn’t needed for production. In other words, these dependencies are only needed for when we are developing our application.

npm install webpack webpack-cli webpack-dev-server @babel/core babel-loader @babel/preset-react  @babel/preset-env html-webpack-plugin --save-dev
  • webpack: webpack is a module bundler.
  • webpack-cli: When building up a custom webpack project, the package webpack-cli (webpack command-line interface) provides a collection of tools to boost speed and efficiency. It provides guidance to create a new webpack project, execute webpack, monitoring file changes, and more.
  • webpack-dev-server: Another command-line interface utility is the webpack-dev-server package. We can start a server with live reload with only one command thanks to the webpack-dev-server package. When we make a modification to the code and save it, the server will immediately reload.
  • babel-loader: babel-loader transpiles JavaScript code.
  • @babel/preset-react : The package @babel/preset-react contains presets for all React plugins. In Babel, a preset is a set of plugins that support language features. By default, Babel has the preset es2015 which adds support for ES6 JavaScript and the preset react which adds support for JSX. JSX stands for JavaScript XML and it allows us to write HTML in JavaScript.
  • @babel/preset-env: The package @babel/preset-env is a preset that allows us to use the latest JavaScript code without having to manage which syntax transforms are needed by our target environment(s). This package will also make our JavaScript bundles smaller.
  • html-webpack-plugin: html-webpack-plugin, which simplifies HTML file creation to serve our webpack bundles. In other words, html-webpack-plugin will assist with adding our bundled files to our index.html file.
Installing Dev Dependencies

Configuring webpack

One of the best things about webpack is how customizable it is. We’ll save all of our settings, loaders, and other build information in a file named webpack.config.js.

  1. Let’s make a file named webpack.config.js at the top of our project structure.

2. We need to export everything from our webpack.config.js file, so we will wrap all the contents of it with module.exports.

3. Let’s inform webpack where our application’s entry point is in our webpack.config.js file . Our application’s entrance point is essentially where our application starts. Our application’s entry point will be a file called index.js located in the src folder.

The key specifies which file webpack should use to generate a dependency graph. A dependency graph is used to resolve dependencies between modules while also constructing modules that are required by other modules first.

4. Let’s make a directory called src and create a file index.js .

5. Then add some React code to it.

We first import our React and ReactDOM libraries. We then import the App component which we will make next. We are then going to be loading our App component into an HTML element with the ID root. This HTML element will be present in our index.html file that we will create soon.

If you are not familiar with React-Dom/Client read this Document.

Note: React Strick mode is a tool for highlighting potential problems in an application. Like Fragment, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

6. let’s Create an App functional Component. To-Do that inside the src make a file App.js and inside that create an App Function.

Side Tip: You are using VS Code you can use an extension called ES7+ React/Redux/React-Native snippets

Create Automatically Arrow function components

7. Then we have to tell the webpack where our Bundle File should be Generated

The name and location of our bundled file will be generated when we produce a production build. This is done with the key output.

Remember that webpack is a module bundler, which means it breaks down large sets of files into smaller parts. When we generate a production build of our React application, we’ll combine all of our JavaScript files into one file called bundle.js.

We want to put this bundle.js file in a subdirectory called dist after it’s finished. We do this by passing the key path to our output object. We next set the output destination of bundle.js to be a folder called dist in our project using the built-in node path module and the term __dirname.

Don’t forget the import the path as follow

Also we need to specify the public path as a output.

PublicPath specifies the virtual directory in web server from where bundled file, app. js is going to get served up from. Keep in mind, the word server when using publicPath can be either webpack-dev-server or express server or other server that you can use with webpack.

8. Then We want our bundled JavaScript file to be loaded into an HTML file.

To do this, we need to make use of the HTMLWebpackPlugin that we installed. To add this plugin to webpack, we need to first require it at the top of our webpack configuration file.

Then let’s register HTMLWebpackPlugin as a plugin in our webpack configuration file. This can be done with the key plugins.

This instructs webpack to inject the packaged files it creates into an index.htmlfile in the src folder. We must ensure that this file is created. In order for our React App component to be loaded, we must additionally construct a <div> with the ID root.

9. Let’s tell Webpack about the loader we’ll be utilizing now. We’ll be utilizing the babel-loader in particular. We start by using the module key and an object as the value.

How various sorts of modules in our project are processed is determined by what we give into this module object. The rules key is then used to provide the module’s creation rules.

Rules are an array of objects where each object is a rule.

First of all, we can create a rule here that we are going to use Babel to transpile all files that end in .js excluding files located in the node_modules directory.

Another thing is with babel-loader using the preset-env and preset-react presets.

10. The next step is to write a few npm scripts to execute our application. One of these scripts will start our program in development mode with a live reload server, while the other will generate a production-ready build.

Let’s assign the npm script called npm start. What this will do is run our webpack-dev-server in development mode.

In the package.json file write the following script.

11. then we can tell, what port number is to run our application, When this development environment starts, we want it to display our application in a new tab open, and also want to add hot module replacement (HMR) to our development environment. HMR exchanges, adds or removes modules while the application is running without requiring a full reload, making our development environment more efficient.

Let’s Assign this configuration to the webpack.config.js .

12. So lets run npm start in the terminal and see what happens 😊!

npm start

13. So now that our development setup is all working correctly, let’s write a script that will create a production-ready bundle of our application.

So lets run npm build the terminal and see what happens 😍!

npm run build

Update Our Previous rule to identifying the both .js and .jsx file.

Disabling the DotRule and Enabling the history Api Fallback

When you are creates routes or a route with a parameter include a dot lead it gets a not found (404) status. To fix that write the following code inside the devServer in webpack.config.js .

Fix some Errors

Adding a Browserlist File

Create a file called .browserslistrc in the main folder and just put default in that file.

This is pretty weird because if you are using babel alone and not in webpack and don’t have any problem without using the browser list. but some away you got a syntax error, you can use this method and solve that problem.

Adding a method that requires a polyfill

Look at above code when we run this, it got an object doesn’t support property or method values error. That’s beacuse this is actually a method that requires a polyfill. to fix that we need a dependencie called core-js . Let’s install that dependencie.

npm i core-js

Then in our Application inside the index.js , import that file.

Getting async await working

When we are using async await , we got a regeneratorRuntime is undefined error. So, to fix that we need to npm install called regenerator-runtime .

npm i regenerator-runtime

Then import it to our index.js file.

Do it Better Way…

Remove what we earlier imported core-js and regenerator-runtime . Then, do some changes in webpack.config.js under the module rule identifying the .js and .jsx files, and edit the presets like this.

Note: Read this Document

Add Some css Supports

Let’s start by adding our styles to our project.

This error is expected. that because use we need an appropriate loader to handle this file.

Let’s install some dependencies.

  • css-loader
  • mini-css-extract-plugin
  • style-loader

The Style loader is going to inject it uh the styles into your javascript bundle whare is the mini css exract plugin is actually going to create resources or a final one single css file for that.

npm i css-loader mini-css-extract-plugin style-loader

Let’s set this up, For that in webpack.config.js import the mini css extract plugin.

Then we are going use plugins in the plugins we going to use new command and call mini css extract plugin constructor.

Then we should assign an additional rule. In this rule going to be looking for css files and step our loarders.

Let’s Check your Output 😊.

Accessing sass / scss Formats

To do that we need to install some dev dependencies.

npm i -D sass sass-loader postcss-loader

Then update the code that we create before.

Let’s check the output 😉.

Accessing css / sass / scss Formats

Accessing images Formats

To access the images known as .jpg , .png,.svg, etc.. We need tell to the webpack. For that, we need to create a new rule like we created to identify the .js and .jsxfiles.

Let’s assign new rule.

Accessing images

If you want to put images for cleanup purposes into an image directory just to be a littile more organized, We can add output path withing output property in webpack.config.js .

Add Title Logo

To do that I choose a random image icon. Then copy to our asserts/images folder and in the webpack.config.js under the plugin property inside the new HTMLWebpackPlugin we can assign as a favicon.

Add a Proxy

To do that we can call the proxy property inside the webpack.config.js like this.

--

--

Amila Devin

BSc (Hons) in Information Technology Specialising in Software Engineering undergraduate at SLIIT