How to Bundle an Application with Webpack

1345 VIEWS

What is Module Bundler

Different technologies such as CSS, JSX, images, and many dependencies we install are crucial resources to build specific software. Module Bundler is a Javascript library that bundles different Javascript modules and dependencies into one single file. At the core, module bundlers collect, transform assets, then output optimized resources. 

Optimization

For optimization purposes, these technologies are bundled up as assets by a module bundler. A bundled application optimises for modularity and network performance. Module bundler makes it possible to divide your application source code into multiple small parts that are reusable, easy to implement, and maintain. We live in an era where everything moves fast; if your application takes forever to load, users will close it and look for the next web application that can load quickly and provide them with information or resources needed. By bundling an application, network performance increases. In other words, the Page Load Time, the total time a request takes to move from the browser, is drastically reduced; hence our network performance is enhanced.

Types of Module Bundlers

Browserify, Webpack, Rollup, and Google Closure Compiler are a few examples of module bundlers. This article will explore a module bundler called Webpack, share with you how to bundle up an application with Webpack. Webpack supports CommonJs, AMD, and ES6 module formatting systems.

 Webpack as a Module Bundler

Webpack takes your Javascript files, dependencies as input, bundles them, and then outputs compressed optimised files. It then constructs a dependency graph for an application that depicts how files and dependencies are organised and how they interact. With the help of powerful plugins, Webpack eliminates repetitive and unused code for optimization purposes. Additionally, Webpack is capable of: 

  1. Code Splitting: This is when Webpack splits up code into chunks decides what resources to throw out at any given time, depending on its demand.
  2. Minification: Webpack removes unnecessary code, variables, and unwanted characters such as whitespace.
  1. Feature Flagging: This is the process where Webpack sends code to multiple environments for testing purposes.
  2. Consistency: Webpack is capable of compiling Javascript, including new Javascript features.  

Prerequisite

  1. Make sure you have Node.js on your machine. Webpack runs on Node.js version 8.0 and higher. It is compatible with other browsers except for IE8. 
  2. Download the latest version of Webpack.
  3. Fundamental knowledge in Node.js is a requirement.
  4. Basic knowledge or interest in React.js will be helpful.

Setup

First and foremost, I will show you a React.js project; then, I will bundle it using the Webpack module bundler at the end. Webpack, React, React-dom, Babel, and other technologies are embedded in “create-react-app”, a tool used for setting up the react project for development; therefore, you do not see what is happening behind the scene whenever you use it. This article explores Webpack in detail. To achieve that, we will be creating a react app from scratch without the create-react-app tool’s aid. Knowing and understanding how to bundle an application is important if you want to be an engineer, not just a developer. Install Webpack, Webpack-cli, React, Babel, and React-dom by running the following commands: 

npm init -y

npm install react react-dom serve

npm install --save-dev webpack webpack-cli

npm install --save lodash

npm install babel-loader @babel/core --save-dev

npm install @babel/preset-env @babel/preset-react --save-dev

 Here is what my project file structure looks like: 

Take a look at the three components I have for my React project, a library that displays books. The  component below books/components/bookDetails.js takes the author and book title as properties: 

import React from "react"

export default function Book({ author, bookName }) {

    return (

        <li>

            {author} {bookName}

        </li>

    )

}

 

Let’s create a component BookList.js that displays list of books, import the component that gives us information about the author and the name of the books:

import React from "react"

import Book from "./bookDetails"

export default function BookList({ bookList }) {

    return (

        <ul className="books">

            {bookList.map((book, i) => (

                <Book key={i} {...book} />

            ))}

        </ul>

    )

}

Lastly, we pass down all the components we created to our library component.

import React from "react"

import BookList from "./BookList"

function Library({ books }) {

    return (

        <article>

            <header>

                <h1>

                    Books in the Library

                </h1>

            </header>

            <div className="books">

                {

                    BookList.map((book, i) => (

                        <Book key={i} {...books} />

                    ))

                }

            </div>

        </article>

    )

}

export default Library

 

Don’t use script tags to add files or libraries such as React and React-dom. Webpack can only add them in the bundled application using the import function. Add the following code in src/components/index.js that will render our component to the DOM:

 

import React from "react"

import { render } from "react-dom"

import Library from ".components/Library"

import data from ".data/myBooks.json"

render(<Library books={data} />, document.getElementById("root"))

Bundling

Let’s say these are all the component I need for my application. The next step is bundling my application. Our bundled application will be stored in books/dist/assets/bundle.js file. Webpack version 5 introduced the webpack.config.js. Here is how our webpack.config.js looks like: 

var path = require("path")

module.exports = {

    entry: "./src/index.js",

    output: {

        path: path.join(__dirname, "dist", "assets"),

        filename: "bundle.js"

    },

    module: {

        rules: [{

            test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"

        }]

    }

}

In the books folder, create a file called babelrc and add the following code:

{

    "presets": [

        "@babel/preset-env",

        "@babel/preset-react"

    ]

}

//presets tells babel to transform the code into a language understood by browser

In the package.json, add the following code that sets the webpack to development or production: 

"scripts": {

    "test": "echo \"Error: no test specified\" && exit 1",

    "build": "webpack --mode production"

  },

Once you are done developing the app, you can bundle it:

npm run build

Here is the output: 

Open the books/dist/bundle.js  directory and you will see the bundled code: 

!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){“undefined”!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:”Module”}),Object.defineProperty(e,”__esModule”,{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&”object”==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,”default”,{enumerable:!0,value:e}),2&t&&”string”!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,”a”,t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p=””,r(r.s=0)}([function(e,t){}]);

Conclusion

Module bundlers bundle all your code into one single file, remove unnecessary code. The essence of bundling your application is to increase network performance and modularity. We uncovered some of the excellent work npx create-react-app tool conduct for us in the background when it comes to bundling an application. You have successfully bundled an application using Webpack; feel free to check out other module bundlers.

 


Primrose Katena is a software engineer, entrepreneur and technical writer. She strongly believes entrepreneurship and technology are positively impacting the world. She has worked in the IT industry in Zimbabwe and Entrepreneurship in Ghana. Ms. Katena loves sharing tech knowledge with other developers through writing.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *