How to Setup Webpack with React.js?

Read it in 15 Mins

Last updated on
19th Sep, 2022
Published
14th Sep, 2022
Views
685
How to Setup Webpack with React.js?

To assist, speed up, and improve our web development workflow, we're now compelled to use a plethora of add-on technologies. Such tools, on the other hand, frequently add to the stack's complexity. As a result, we will need to devote more time and effort to learning, comprehending, and properly employing these technologies. For webpack, the same is true.

It can be challenging to comprehend how webpack works and how to utilize it while using it for the first time. It has extensive documentation, but it can be intimidating for newcomers and has a steep learning curve. Webpack, on the other hand, is worth learning because it can save you a significant amount of time and effort in the long run. I'll go over all the fundamental ideas here to help you get started. 

To understand React JS completely you can refer to React JS training. 

What Is Webpack in React?  

In order to comprehend Webpack, it is normally a terrific concept to begin the usage of Grunt and Gulp. In Grunt jobs and Gulp pipelines, file paths are utilized as input (globs). The matching documents may be subjected to quite a few methods. Commonly used operations encompass transpile, concatenate, minify, and others. This is an extremely good concept, however, neither Grunt nor Gulp is familiar collectively in conjunction with your project's structure. When in comparison to Webpack, Gulp and Grunt deal with documents, whilst Webpack deals with projects.

Webpack allows you to specify a single path. The route that leads to your entry location. Typically, index.js or main.js are used. Your application is now being investigated by Webpack. It will figure out how everything is connected using lines like require, import, etc., URL values in your CSS, and href values in image tags, among other things. It generates a complete dependency graph of all the assets required for your app to run. It's all pointing to the same file. 

Webpack, regularly called module bundler, is a device for compiling JavaScript modules. It generates a single file (or a few files) that runs your app from many files. 

It has a wide range of capabilities, including the following: 

  • Aids in resource bundling 
  • It keeps an eye out for changes and re-runs the jobs if necessary. 
  • Can use Babel to convert to ES5, allowing you to leverage the latest JavaScript capabilities without having to worry about browser compatibility. 
  • CoffeeScript to JavaScript conversion is possible. 
  • May make data URIs out of inline pictures 
  • Allows you to utilize CSS files using need(). 
  • Can run a web server for development. 
  • Can be used to change modules in a hurry. 
  • To prevent having a large JS file load on the initial page click, you can break the output files into numerous files. 
  • Tree-shaking capabilities 

For more information about React JS check out our other blog post - How to Learn React

Why Should You Use Webpack? 

The administration of modules in a JavaScript project is made easier using create react app Webpack 5. Although most modern browsers that are ES5-compliant (Chrome, IE, Edge, Firefox, Safari, Opera etc.) allow modules out of the box, compiling them using webpack offers some additional advantages. 

Support for loaders is one advantage of utilizing webpack. Webpack uses loaders to support types other than JavaScript and JSON, such as CSS. They can also change files before or during the bundle creation process. For example, babel-loader converts next-generation JavaScript syntax to universally compatible syntax, allowing you to access the most recent JavaScript capabilities without having to rewrite your code. 

The ability to minify your project's code is another advantage of utilizing create react app Webpack version. Webpack react app may eliminate any inessential parts from your code, such as whitespace and comments, while building in production, resulting in a considerable reduction in project size. 

Also, check out the web development courses online with certificate to get your hand on react and its properties. 

React Webpack Components 

Below, we'll go through a few of the most significant webpack fundamental components. 

  • Loaders 
  • Dev Server (webpack-dev-server) 
  • Plugins 
  • Entry
  • Output 

Entry  

  • Webpack constructs a graph for all application dependencies from this point.
  • This entry point instructs the webpack where to begin and what to bundle by following the dependency graph. 
  • The entry attribute of the module.export method is defined in the "webpack.config.js" file. 

Example 

module.exports =    
{    
   entry: "./src/index.js"    
}    

Output  

  • After you've packed all your assets together, you'll need to tell webpack where to bundle your application. 
  • The output attribute instructs webpack on how to handle bundled files. 

Example 

module.exports = {   
    entry: "./src/index.js"   
    output: {   
        path: "Idist/assets",   
        filename: "bundle.js",   
        publicPath: "assets"   
    }   
}    

Loaders  

  • Rather than the browsers, webpack should oversee all assets in the project. 
  • Even though it only understands javascript, Webpack considers every file (html,.css,.scss, jpeg, etc.) to be a module. 
  • Loaders have two functions in webpack.config. 
  • Determine which files should be transformed by a specific loader. (property "experiment") 
  • Change the file so that it may be used in the dependency graph (and eventually bundle). (the "loader" property) 
  • Webpack's loaders convert files into modules when they are added to the dependency graph. 

Example 

module.exports = {   
    module: {   
        loaders: [{   
            test: /\.(js|jsx)$/,   
            exclude: /(node_modules)/,   
            loader: 'babel-loader',   
            query: {   
                presets: ('es2015', •react, 'stage-Ol']   
            }   
        }, ]   
    }   
}    

Dev server – webpack-dev-server  

  • It can be used to construct an application quickly. 
  • It includes a server as well as real-time reloading. 
  • Unless the developer expressly configures a specific content base, it will save the files in the current directory by default. Inline mode is a mode that allows you to work while (a small webpack-dev-server-client entry is added to the bundle which refreshes the page on change) 

Example 

module.exports = {   
    devServer: {   
        inline: true,   
        contentBase: './dist',   
        port: 8080   
    },   
}; 

Plugins  

  • Plugins are most used (but not limited to) performing actions and custom functionality on "compilations" or "chunks" of your bundled modules, whereas loaders only do transforms on a per-file basis. 
  • Webpack comes with a robust plugin interface. This plugin interface is used by the majority of webpack's functionality. Webpack is more adaptable as a result of this. 

Example 

query: {   
    presets: Ces2015 ', '   
    react ', •stage-m,   
    plugins: ['react-html-attrs'],   
}  

Understanding How React Webpack Works? 

We'll study webpack's capability on this part. Even the handiest mission incorporates HTML, CSS, and JavaScript documents. It may also encompass such things as fonts, photographs, and different visible elements. A fashionable webpack react app method might encompass developing an index.html record with all the critical CSS and JS links, in addition to the desired property. Furthermore, when you have a massive variety of CSS and JS modules that can be interdependent, they should be optimized and accurately merged right into a single unit. This is appropriate for production. 

Webpack react app is primarily based totally on the configuration to do all of this. Webpack gives appropriate defaults out of the container beginning with model four and above, so there may be no want to create a configuration record. You'll want to offer a particular webpack.config.js record for each non-trivial mission and that is the reason for how the documents and property ought to be transformed and what type of output ought to be created. This record can also additionally quickly grow to be monolithic, making it hard to understand how webpack works except if you recognize the essential standards that underpin it. 

Webpack constructs the dependency graph via way of means of beginning from the access factors and resolving every module it reveals primarily based totally on the settings. If a module consists of dependents, the operation is repeated for every dependence till the traversal is complete. Then, with the usage of webpack, all the mission's modules are bundled right into a minimum variety of bundles — usually the handiest one — that the browser can load. 

For more details and explanations, you can refer to the web development courses online with certificate to get help from our experts. 

How to Use Webpack with Create React App? 

Install Webpack in React 

For each project, Webpack may be deployed globally or locally. 

Global Install  

Here's how to use Yarn to install it globally: 

yarn global add webpack webpack-cli 

with npm: 

npm i -g webpack webpack-cli 

You should be able to run after this is completed. 

webpack-cli 

Local Install  

Webpack may also be installed on a local machine. Because webpack can be updated per project, you'll be less hesitant to adopt the latest features on a tiny project rather than updating all your webpack-using projects. 

With Yarn: 

yarn add webpack webpack-cli -D 

With npm: 

npm i webpack webpack-cli --save-dev 
Add this to your package after it's finished. json document: 
{ 
//... 
"scripts": { 
"build": "webpack" 
} 
} 

After that, you can execute webpack by going to the project root and entering in the command. 

yarn build 

Set Up Project Structure  

Get the Project started 

Let's start by making an empty project and installing a few dependencies. Make a directory and then execute it. 

npm init –y 

to get your new project started This should result in the creation of a default package. Manifest.json is a json file. 

You may omit the -y parameter and begin the project in any way you choose. 

Let's get started by installing some of the essential packages we'll be using: 

  • React is the maximum critical react library.
  • webpack — the JavaScript bundler we're going to be searching at extra under
  • webpack-cli — a device that permits us to run webpack instructions from the command line 
  • react-dom — the bundle that permits us to apply React withinside the browser

Run the following commands to install them all: 

npm i react react-dom 
npm i -D webpack webpack-cli 

Package.json and package-lock.json files should already be present in your root directory at this time. Now make a few empty files that we'll fill in later, and set up your project to look like the one below: 

 
TUTORIAL-REACT-WEBPACK 
REACT-WEBPACK 
└───src 
│ └───App.js 
│ └───index.js 
| └───index.html 
| └───index.css 
└───package-lock.json 
└───package.json 
└───webpack.config.json 

Create a Simple React App 

To get started with webpack react app, that's pretty much all we need to know. Let's go ahead and add some code to those files we made before so we can test them in the browser. 

<!DOCTYPE html> 
<html> 
<head> 
<title>React with Webpack</title> 
</head> 
<body> 
<div id="app"></div> 
</body> 
</html> 
import React from "react"; 
import ReactDOM from "react-dom"; 
import App from "./App"; 
ReactDOM.render(<App />, document.getElementById("app")); 
import React from "react"; 
export default function App() { 
return <h1>Hello Friend</h1>; 
} 

This application's sole purpose is to generate a heading tag that displays 'Hello Friend' on the page. However, if you try to include index.js in your HTML usage. 

... 
<script src="index.js" /> 
</body> 
</html> 

It's not going to work. If you open it in a browser, you'll see nothing but a blank page. 

This is due to the browser's inability to import an App from "./App." The browser can only load static JS files, therefore let's use webpack to turn our application into something that the browser can comprehend. 

Utilizing Loaders 

Install babel-loader first, which allows us to convert JSX into browser-friendly JavaScript. Run the following commands to do this: 

npm i -D @babel/core @babel/preset-env @babel/preset-react babel-loader 

To load our JSX files, we installed babel, two presets, and then the loader. To understand more about what these settings accomplish, see to the babel documentation. 

Configure React-webpack  

Now we can tell webpack to utilise Babel to parse any JSX files during bundling. 

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

Bundle Your React App 

Let's finish our package by adding a script. We're using json to make it easy to construct our app anytime we want. 

{ 
"name": "tutorial-react-webpack", 
"version": "1.0.0", 
"description": "Configuring webpack for React", 
"main": "index.js", 
"scripts": { 
"build": "webpack" 
}, 
"keywords": [], 
"author": "", 
"license": "ISC", 
"dependencies": { 
"react": "^17.0.2", 
"react-dom": "^17.0.2" 
}, 
"devDependencies": { 
"@babel/core": "^7.13.16", 
"@babel/preset-env": "^7.13.15", 
"@babel/preset-react": "^7.13.13", 
"babel-loader": "^8.2.2", 
"webpack": "^5.35.1", 
"webpack-cli": "^4.6.0" 
} 
} 

Run The Bundled Application 

<!DOCTYPE html> 
<html> 
<head> 
<title>React with Webpack</title> 
</head> 
<body> 
<div id="app"></div> 
<script src="../dist/main.js"></script> 
</body> 
</html> 

Does React Need Webpack? Benefits of Using React Webpack 

We don't have to use webpack to operate with React; other options include Browserify, Parsel, Brunch, and others. 

1. React Build Systems: Complete Control 

The most significant issue with the current code is that it is difficult for older browsers to comprehend it. HTML, CSS, and JavaScript are utilized in basic browsers, but React uses JSX and ES6+ code. When you use React webpack, you have total flexibility and the option of using create react app Babel or Traceur to transpile your current code to earlier browser versions. This might put you ahead of your competitors straight away. 

2. Improves the scalability of your React application 

Because React Webpack is a module system, it can aid in the scalability of your react. Webpack is a module system built on top of the ES6 standards. When you use this module system to create a file, it becomes a module with its own scope by default. If your project is reliant on a variety of vendors, this is quite useful. React developers may also learn how front-end boilerplates function beneath the hood by using Webpack React app. 

3. With hot module replacement, you may cut down on development time 

The 'Hot Module Replacement' feature of React with Webpack is a promising feature. One of the most uncomfortable and annoying situations in internet improvement has been whilst changes made to the internet programme do now not render as intended. This forces the developer to restart the net web page so that you can see the most modern-day changes to their net project. Many developers have created plugins and gadgets to control the DOM such that it re-renders each time the developer saves changes without requiring an entire reload.

In React, this is known as Hot Reloading, and it includes converting a selected app module with an updated one at some unspecified time in the future of runtime simply, so it can be used right away as needed. Hot Module Replacement takes it a step similarly way of disposing of the requirement for a web net web page reload to mirror minor changes for your JS or CSS code. In the create react app webpack config file, you want to feature CSS loaders. Furthermore, debugging reduces the time it takes to load a web page. By reducing the standard improvement time, this substitute possibility accelerates the publishing of your net web page. 

Pros and Cons 

Pros 

Cons 

  • Working with single-page apps is a breeze with this program. 
  • The require() and import module syntaxes are both supported. 
  • It's possible to separate code in a complex way. 
  • React, Vue.js, and other frameworks can benefit from Hot Reload for faster development. 
  • According to a 2016 JavaScript poll, the most used build tool is. 
  • This is not a good place to start if you are new to web programming. 
  • Working with CSS files, pictures, and other non-JS resources can be perplexing at first. 
  • Changes frequently; in fact, most 2016 tutorials are now out of date. 

Conclusion 

This concludes our discussion on React Webpack. If you're working on a huge app project that requires customization, scalability, and extensive configuration, make sure to use webpack with react to ensure that your react app can handle all the demands and runs without any bottlenecks. If you want to improve your React skills quickly, kindly check it out knowledgeHut’s React JS course online

Here is a tutorial that explains create react app - Using npm create-react-app. 

Frequently Asked Questions (FAQs)  

1. Should I use webpack or create react app? 

You can use Webpack with Create React App. 

2. How do you add a webpack to react app?  

While it makes use of Webpack at the back of the scenes, the person isn't given get entry to the WebPack configuration till you pick to eject it. 

3. Does create react app use webpack-dev-server?  

The server is solely meant to be used for testing purposes. 

4. How do I upgrade my webpack version? 

  • npm: npm install webpack@latest. 
  • Yarn: yarn add webpack@latest 

5. What is the difference between webpack and babel?  

Webpack belongs to the "JS Build Tools / JS Task Runners" category, whereas Babel belongs to the "JavaScript Compilers" area. 

Profile

Geetika Mathur

Author

Geetika Mathur is a recent Graduate with specialization in Computer Science Engineering having a keen interest in exploring entirety around. She have a strong passion for reading novels, writing and building web apps. She has published one review and one research paper in International Journal. She has also been declared as a topper in NPTEL examination by IIT – Kharagpur.