The Webpack tool is a very popular tool these days. As a web developer. I think it is an important skill to know about React Webpack. How to read and understand documentation. When you are learning React or you are just a beginner. You create an App using create-react-app. But this method abstracts away the project setup. Perhaps abstraction is not something always we want. Using React webpack we can get complete control of all the configurations in the React App. In this tutorial, I’m literally just going to walk you through step by step the documentation. Also, I’ll be showing you examples along the way and details about the webpack.config.
Recommended: How to Use Location Hook in React Router DOM V6
What is Webpack 2?
Webpack is a module bundler for JavaScript applications. It takes modules with dependencies and generates static assets representing those modules. In simpler terms, Webpack helps you manage and optimize your JavaScript code, stylesheets, and assets.
Webpack 2 is the second major version of this tool and comes with significant improvements and enhancements over its predecessor. It offers a more streamlined configuration, better performance, and enhanced code-splitting capabilities.
How you can use Webpack in a React.js project
If you want to integrate styles, some other packages or plugins. You can use webpack. In this tutorial you will learn how a loader works, how a plugin works, and most importantly, You will understand how to navigate the documentation.
So It’s a module bundler for JavaScript applications, styles, and assets.
The above diagram actually gives a really good description of what webpack does. It’s going to take all your files, all your assets, whether that’s SAS files, access handlebars, JavaScript files, JPEG photos, fonts, whatever, all the different assets that you need for your project, that’s going to take all of these things. And what it really does is it manages dependencies like it says down here, modules with dependencies. So it keeps track of all these different files who rely on all these different files and all these different assets. And then it goes through the Web. Then at the other end, webpack can output a single JavaScript file or multiple single access files.
Recommended: Redirect to Component with Props Using useNavigate Hook
Key Features of Webpack 2
Let’s dive into some of the standout features that make Webpack 2 a game-changer for web developers:
1. Code Splitting
The webpack 2 introduces improved support for code splitting, allowing you to load only the code needed for a particular page or feature. This can significantly improve your application’s load times, especially for large-scale applications.
2. Tree Shaking
With Webpack 2, you can perform dead code elimination through a feature called “tree shaking.” This means that only the code that is actually used in your application will be included in the final bundle, reducing its size and improving performance.
3. Better Configuration
Webpack 2 simplifies configuration with a more intuitive setup. You can use ES6 module syntax for configuration, and the default configuration settings have been optimized for most common use cases, reducing the need for extensive custom configurations.
4. Improved Performance
The webpack 2 is faster and more efficient than its predecessor. It optimizes builds, resulting in shorter build times, which is crucial for a smooth development workflow.
5. Asset Management
Webpack 2 can handle various assets, including images, fonts, and CSS, making it a comprehensive tool for managing all your project’s assets.
Now that we’ve covered some of the key features, let’s briefly outline how to get started with Webpack 2.
Recommended: How to Deploy a React Application on a cPanel in a Subdirectory
Step 1 – Create a Folder REACT-TEMPLATE
Then run the below command. This will create the package.json file inside the react-template folder.
npm init -y
You can change the author’s name and license if you wish to change. Again, none of this really matters.
Step 2 – Install Webpack
You can install Webpack 2 globally or locally to your project using npm or yarn
npm add -D webpack
It will add the webpack dependencies in the package.json file. Here, the webpack version is 5.88.2
Recommended: How to Create Todo App in React JS Using Redux
Step 3 – Create another folder src and dist
Inside the src folder create an index.js file. After that inside the dist folder create an index.html file.
In the index.html file place the code
<!DOCTYPE html>
<html>
<head>
<title>Webpack Config</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
In the index.js file place the code
console.log('Hi from Webpack');
So if we want to use an index.js file then we need to create a bundle of index.js. For creating a bundle we need the webpack.config. Therefore, let’s create it.
Step 4 – Create a webpack.config.js file in the root folder
webpack.config.js: This is the configuration file that webpack is going to read in order to use all the things that we need for our project.
const path = require('path');
module.exports = {
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname, 'dist')
}
}
Firstly, we need to do is create this path variable. This is going to help us to know where to check, that the files are located. So the first thing is going to be a module that exports. After that, an entry and the entry is ‘./src/index.js‘. Now, this is the entry point for React webpack.
Therefore, this would be the main file and webpack.config is going to look for. So all of our applications and everything is going to come through this entry point. After that, it would make sense within the output point.
Output is basically once. So our source code is going to be in this entry point. Where it’s going to pull this. In the web is going to do its magic that really we’re going to tell webpack.config. What to do and then we need to tell webpack once Here’s the output.
Step 5 – Output Bundle.js File
Firstly, we need a filename. Once we’re done, we’re going to call it the bundle.js. You can call it anything you want. But that’s kind of like standard.
Here, basically what this is saying is, here’s my entry point. When you’re done, you’re going to rename the file bundle.js. Where you put it into the dist folder. Once done, run the command npm run build. This will create the bundle.js file inside the dist folder.
Now bundle.js file has the access to index.js file. Once the bundle is created open the index.html file in the browser. We will see the message in the console Hi from Webpack.
So that’s simple, We just created our first Webpack bundle.
Recommended: How to Use Routing in React JS Using React Router V6
Loaders in webpack
In webpack, loaders are a fundamental concept that allows you to preprocess files as they are bundled together in your application. Loaders transform files from one format or type into another. This transformation can include tasks like transpiling JavaScript from newer versions to older versions, compiling SASS or LESS into CSS, or even optimizing and compressing image files.
Loaders are applied to specific files or sets of files in your project, depending on the rules you define in your Webpack config.
Installation: To use loaders in Webpack, you first need to install the necessary loaders using npm or yarn. Add the below command.
npm add -D style-loader css-loader
Now we need to update the webpack.config.js
const path = require('path');
module.exports = {
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname, 'dist')
},
module:{
rules:[
{
test: /\.css$/,
use:[
'style-loader',
'css-loader'
]
}
]
}
}
Inside the src create a css folder and create main.css inside it. Here, you can write some styling inside main.css.
body{
background:green;
}
Now, import this CSS file inside the index.js file. This will change the background color of the webpage.
Setup Sass in webpack.config.js
For the setup of sass, we need a sass loader and node-sass. Run the below command in the terminal.
npm add -D sass-loader node-sass
After installing Sass we will write a test in the webpack.config.js file.
const path = require('path');
module.exports = {
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname, 'dist')
},
module:{
rules:[
{
test: /\.css$/,
use:[
'style-loader',
'css-loader'
]
},
{
test:/\.scss$/,
use:[
{loader:'style-loader'},
{loader:'css-loader'},
{loader:'sass-loader'}
]
}
]
}
}
Create a new folder scss inside the src folder. After that import the folder inside the index.js.
// import './css/main.css';
import './scss/main.scss';
console.log('Hi from Webpack');
Write style for sass inside the main.scss file.
$blue : orange;
body {
background: $blue;
}
Now run the command npm run build. This will change the background color.
So, we are injecting a sass file in the javascript.
Recommended: How to use Redux, React Redux in React JS with Example
Add Babel for Using the Latest Javascript Version
In order to add Babel you will have to run the below command.
npm add -D babel-loader babel-core
This command will install the babel-loader. Now give the new object to the React webpack.config.js file.
const path = require('path');
module.exports = {
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname, 'dist')
},
module:{
rules:[
{
test: /\.css$/,
use:[
'style-loader',
'css-loader'
]
},
{
test:/\.scss$/,
use:[
{loader:'style-loader'},
{loader:'css-loader'},
{loader:'sass-loader'}
]
},
{
test:/\.js$/,
exclude:/node_modules/,
loader:'babel-loader'
}
]
}
}
We will exclude the node_modules to be processed. But, here we only want our files to be processed.
We will also have to create a babelrc file. This is going to allow configure the types of things that you want available to Bable. For this install below command
npm add -D babel-preset-env
Add the JS folder inside the src folder. And create a module.js file.
Import the module.js file inside index.js
import{ welcome, hello } from './js/module';
welcome();
hello();
Now run the command npm run build and check the output in the console.
Now we got the message from the module.js file and we are able to use ES6.
There are lots of loaders that can be used according to your needs. Now you can easily set up your React webpack file.
Recommended: How to Install and Setup Redux in React JS Step By Step
Save Webpack Automatically – Watch
We have seen whenever there is a change in the files, we have to write the npm run build command. So this is kind of annoying. So here I will show you that we can save the files automatically and we do not need to run the command in every single change.
React webpack has a feature called a watch. You can add it to the package.json file. It is called a flag. And this way it’s going to watch our files every time we save. It’s just going to automatically run and bundle things together. We’re going to create a new script.
And now run the command npm run watch
Every time you’re making a change, React webpack will just sit there and watch. We can have it automatically reload our browser so that every time it’s going to watch it sees that change. It’s going to automatically refresh, and that’s just going to make our development lives a whole lot easier. I am attaching my GitHub link to download the source code.
Conclusion
Webpack 2 is a powerful and versatile build tool that has become an integral part of modern web development. Its features, performance improvements, and enhanced configuration make it a valuable asset for building efficient and optimized web applications. If you’re not already using Webpack 2, now is the time to dive in and explore how it can streamline your development process and deliver better-performing web apps. Happy coding!
Leave a Reply