Webpack: The advantages and how to set it up for React

All of us have used CRA (create-react-app) when we worked with React. It’s an awesome tool because it gives us just to focus on React by letting us take care of the configuration. Webpack is one of those great tools for working with React. Though this module feels like this huge and unnecessary thing that you just must learn and use if you wanna build a modern web app, yet it’s one of the most important things that help you a lot when using React.

If you are heading towards using Webpack with React for your business, then this article will be just for you! So now, we – ArrowHiTech would like to introduce to you guys some major advantages of using Webpack with React, as well as the steps on how to set it up for React.

But first, let’s go through some definitions.

What is Webpack?

 Webpack

It’s certainly a module bundler which lets us bundle our project files into a single file. It also requires a webpack.config.js file in the root folder. Where we tell our Webpack how to work with our application, can be done by giving entry point information and also output information. The “entry” point, to clarify, is where our application is going to kick off and we set it by giving relative path value. And moreover, the output property tells where to emit the outputs and how to name those files.

Why use Webpack for your projects?

 Webpack

#1. The module gives you a modern system

A module system is essential to any programming language that is built for scale. With Webpack, your module system that is based on the ES6 standard (it actually supports many module systems standards, but the most modern is ES6) will be highly supported. Also, by having this module system, every file you create is automatically its own module with its own scope. As a result, this is notably effective if you start using more and more dependencies.

As a result, this module automates the process of downloading/including modules as we have mentioned above, so it’s being used often in the frameworks/libraries. Not only that learning this application will allow you to gain the benefits mentioned earlier, but you will also understand how front-end boilerplates work under the hood. Therefore, understanding the modern front-end ecosystem will be of no struggling task for you.

Read

Flux: The basic knowledge and how to implement flux pattern in React app

Lottie: Create better user experience (with animations) for React Native

#2. The development can be sped up when using Webpack

Development time has also been improved thanks to this module’s feature called “Hot Module Replacement”. This has been proven to boost productivity because your page doesn’t need to trigger a full reload just to reflect your changes on your Javascript code. It will not only apply to Javascript, but your CSS code can also benefit from this feature by adding CSS loaders in your webpack config. So, this makes your development time much faster.

In addition, the time it takes for the page to fully load while debugging is also reduced. As mentioned above, your page doesn’t need a full reload (which causes tons of downtimes) just for the changes consequently. The “replacement” is the cause to reduce the development time, and as a result, speed up the publishing time of your website.

#3. You can set up single-page applications better while using Webpack

You can actually see the benefits of using this module, especially if you’re developing single-page applications. When you learn everything about webpack, you will easily be able to set up a single-page application. This is especially true when you’re using React since this module can use transpilers such as Babel alongside it to transpile JSX syntax into readable Javascript code.

#4. Total control over building syste

You can choose various build systems you’ll need with this module if there are any such as using Babel or Traceur via Webpack loaders if you need to transpile your ES6+ code in previous versions to make your Javascript code compatible with older browsers. Either way, you certainly have control over it. This is efficient for your business because you will have the leading position to put your website on the right track.

How set up for using Webpack with React?

Now we know a little bit about Webpack. So, let’s dive into using Webpack with React setup.

 Webpack react

#1. Getting started for using Webpack with React

You should certainly create directories with these commands first:

 mkdir react-setup-tutorial
cd react-setup-tutorial
mkdir public src
touch public/index.html src/app.js

In index.html file add the following code inside it.

   <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>React App</title>
      </head>

      <body>
        <div id="root"></div>

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

Further, you should initialize the project by running:

npm init -y

#2. Install Webpack and React for using Webpack with React

npm install webpack webpack-cli --save-dev

We installed webpack-cli so that we can use this module in the command line. We certainly know by now that this module needs the module’s config.js to file at the root of the project directory. So let’s create this kind of file with the following code inside it.

 const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  }
};

After that, add the webpack command inside package.json:

 "scripts": {
    "start": "webpack --mode=development",
    "build": "webpack --mode=production"
  }

To clarify, there are two modes in this module, development, and production, in which we can set by – mode flag. Also, production mode produces optimize files that are ready for use in production.

Install React:

npm install react react-dom

Now import react and react-dom inside our app.js file and also add some react code.

 import React from 'react';
 import ReactDOM from 'react-dom';
 const template = React.createElement('p', {}, 'Hello from react');
 ReactDOM.render(template, document.getElementById('root')); 

Now use below command in your terminal and open your index.html file in your browser subsequently.

npm start

#3. Configure source map while using this module

So, let’s add some extra configuration settings in our file.

 const path = require('path')
 module.exports = {
   entry: './src/app.js',
   output: {
     path: path.join(__dirname, 'public'),
     filename: 'bundle.js'
   },
   module: {
     rules: [
       {
         test: /\.js$/,
         exclude: /node_modules/,
         loader: 'babel-loader'
       }
     ]
   },
   devtool: 'cheap-module-eval-source-map'
 };

Here we set up a Source map by using the devtool property, so we can enhance our debugging process. Its use to display our original JavaScript while debugging, which is a lot easier to look at than a minified code.

#4. Install DevServer

Firstly, run this below command in the terminal.

npm install webpack-dev-server --save-dev

Add the following code inside the webpack.config.js file.

 const path = require('path');
 module.exports = {
   entry: './src/app.js',
   output: {
     path: path.join(__dirname, 'public'),
     filename: 'bundle.js'
   },
   module: {
     rules: [
       {
         test: /\.js$/,
         exclude: /node_modules/,
         loader: 'babel-loader'
       }
     ]
   },
   devtool: 'cheap-module-eval-source-map',
   // changed line
   devServer: {
     contentBase: path.join(__dirname, 'public')
   }
 }; 

After that, add webpack-dev-server command inside package.json:

 "scripts": {
    "start": "webpack --mode=development",
    "build": "webpack --mode=production",
    "dev-server": "webpack-dev-server"
  }

Now run this command.

npm run dev-server

It’s going to start the development server. And also it gives us output where we can access it. Now we have integrated both tools into one, the dev server is our server, and its also running this module for us.

#5. Loading the styles for your Webpack

Use the following command to create a file and folder.

 mkdir src/styles
touch src/styles/styles.css

Now add the following styles inside styles.css file.

 * {
  color: blue;
}

To load our style.css file we certainly need to set up new rules in the config.js file. Before that, we need to install some new loaders.

npm install css-loader style-loader --save-dev
  • css-loader: Allows this module to load our CSS assets.
  • style-loader: Take CSS and adds it to the DOM by injecting a <style> tag.

After that, add new rules in this kind of file.

Finally, you are allowed using Webpack with React.

Final words

That should be it! To conclude, here are some advantages of installing Webpack and how to set it up for using Webpack with React. Throughout this small introduction, you can start to tinker with this module’s configuration and create a setup that is ideal for you and your JavaScript web application workflow. Therefore, your website will be more completed and will be much more flourished.

Please visit ArrowHiTech Website to find our more awesome Development Services. Besides that, you can get FREE ASSISTANCE from ArrowHiTech’s Experts working 24/7. So that is your seldom opportunity. Don’t miss it.

Tags

Share