Webpack + Performance Optimization

Webpack + Performance Optimization

·

8 min read

By the end of this blog you will have an idea what is webpack and how you can make your web apps faster.

Without wasting any time let's start.

So consider the example below we are having 3 script tags.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webpack</title>
</head>
<body>
        <div id="root"></div>    
      <script src="./app.js" ></script>
        <script src="./index.js"></script>
        <script src="./sums.js"></script>
</body>
</html>

There are two problems :

  1. Most of the libraries today are all npm install,yarn install and we can't even find some script tags for some libraries so what we will do ?

  2. We can see that index.js needs app.js so the app.js is needed to be in the global scope. In the same way, sums.js depends on index.js so index.js needs to be above sums. Let's say we need lodash tomorrow we will need to include it at the top. So we need to maintain a dependency graph manually which is not good. If something is misplaced our application breaks.

Now someone will think that if each script is dependent upon each other then why not write everything in one script. So to answer this it is a big NO and it is not possible. We want to write code that is modular means in separate files. To fix this we use WEBPACK.

What is Webpack then?

Webpack is a module bundler for modern JavaScript applications. It bundles multiples JS/CSS files that are needed by our app to run in one big file. The dependency graph is also maintained when all the files are processed depending upon the import/export statement that is given in the files. It also saves us from the headache of maintaining the graph.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webpack</title>
</head>
<body>
    <div id="root"></div>
    <script src="./main.js" ></script>
</body>
</html>

So after the webpack is configured there will be one script tag and it will have all the other files which are dependent upon each other and it also takes care of the dependency graph internally.

Understanding Webpack

Webpack doesn't understand JSX. It only understands import/export. It doesn't understand ES6+code. It will copy and paste and if the browser doesn't understand ES6 it might cause an issue. Our browser doesn't understand Typescript code, JSX code everything needs to be converted. So to overcome this issue Webpack sends the code to babel.

What is Babel?

Babel takes care of the files like .jsx , .tsx and converts them into javascript. So the process of converting code into pure javascript so that our browser can understand is called transpilation which is done by babel.

React code which browser doesn't undestand :

function App({name}){
    return <h1>Learning Babel !!{name}</h1>
}

Babel converts it so the browser can understand it :

function App(_ref) {
  var name = _ref.name;
  return /*#__PURE__*/React.createElement("h1", null, "Learning Babel !!", name);
}

You see the above code we don't want to write code like this. We want to write our code with the latest syntax and the best javascript code ever. So to understand our code the webpack sends the code to the babel and babel converts it so the browser can understand.

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments.

Some browsers may not understand arrow functions, const, let so babel takes care of this also.

For Example :

///Some old browsers may not understand this
const a = 5;
let b = 6
const hello =()=> console.log("Babel")

Now every browser will understand :

///So babel converts the code so that every browser can understand it
var a = 5; // const gets converted into var
var b = 6; // let gets converted into var
var hello = function hello() {
  return console.log("Babel");
};

All of this is done beautifully by BABEL

Let's talk about Performance

Gif description

Code splitting

So let's take the example above i.e After we included webpack everything is being bundled to one file main.js. Webpack bundles all the JS/CSS files into one big file. This made the file big and it also increased the KB/MB. So downloading a big file will slow down the browser.

So for understanding purposes let's say the main.js is to be 70kb. So when the client opens the web app the entire 70kb needs to be downloaded within a go and then only the client can interact with the page. Rather than downloading 70kb within a go, we can break the code into small bundles. So the most important bundle will be downloaded first. And the bundle which needs to be downloaded after the user interacts can be downloaded at that time. So why this is needed?

Let's suppose the client internet is 3g. So if the client opens the web page and the 70kb file will take some time to be download by the browser, the client will stare at a blank screen till the page loads. We don't want our clients to run away from our website.

Gif description

So when we break the code into small bundles say 70kb is broken into 40kb and 30kb. Let's say the 40kb is downloaded first and the 30kb is downloaded when the user interacts. This way, the client with a 3g network doesn't need to wait for a long time or stare at the blank screen. The bundles will be downloaded easily and within less time. Because downloading a 70kb file will need more time than downloading a 40kb file. This is also called lazy loading. We load something ( download the bundle) when the client requests it. It helps in performance optimization where the network issue exists.

Minification

Minfication is the process of minimizing code and it also includes removing all whitespace, comments , semicolon from our code.

Before minification:(SIZE: 192b) :

//Before minification
//Hi lets learn minification !!!
function addition(a,b){
return a+b
}
addition(4,5)/// it will print out 9
function myName(name){
 console.log("My name is "+ name)
}
myName("pratim")

After minification:(SIZE : 120b) :

function addition(n,i){return n+i}function myName(n){console.log("My name is "+n)}addition(4,5),myName("pratim");

image.png I am groot

Why minification?

Minification improves the site speed and user interaction. It also improves the website experience which makes both the user and the search engines happy.

Why not write minified code?

Javascript code is written by humans. So to understand the code of one human by another human whitespace, formatting, comments are needed which helps in understanding and debugging.

So the minified code is smaller than the original code and it also helps to reduce the size of the code by some percentage which helps in performance optimization also.

In the above, before minification, the size was 192b and after minification, it is 120b. Which is pretty awesome. It removes comments, whitespace, semicolon which improves performance. Only the minified code is shipped to the production.

javascript-minifier.com → Check out how the code gets minified here.

Chunking

In the first part, we saw that webpack bundles all the different files in a single file named main.js .But with time this file will get bigger and bigger and every time the browser needs to download this big file it slows down. So to improve this chunking is done. Chunking is basically breaking down the file into smaller pieces.

Versioning

In the above example, we have one big file main.js we have broken down that file into smaller chunks. But there is a problem now. Everytime the client requests for something the files get downloaded again and again which is not good. We want our client to download the files obviously but what is the point of downloading everything again and again when the client visits that particular website. So here versioning comes in the picture.

Versioning is done by doing a hash of the chunk i.e VERSION and appending it into your file which will be cached in the browser. When we break down the file into pieces change in one piece doesn't affect the other piece. So only the changed piece will be downloaded by the browser next time and the unchanged pieces will be taken from the browser's cache.

Caching

Caching is very important without caching there will be hard times working on the web when the data is not good at some places and in the previous era when the internet was not that good enough. Because the internet is very costly even now and many people from some parts of the world may not have that much money to pay for it .

So caching plays an important role here. Caching means if a file is downloaded (or say bundle) if its name is not changed the browser doesn't download it again. It uses the file from the browser cache. Browser is smart enough to do this.

_ Fewer the downloads by the browser faster the page loads

So caching and versioning comes hand in hand. We don't want the client to download the files which are not changed so caching and we don't want our client to miss out on something we pushed so versioning.

So we have come to the end of this blog. Hope you got some idea about webpack and performance. Do comment down your thoughts below this will help me writing more and better blogs.

Resources

Optimise your web app to gain 3X speed!

Webpack

Babel

Tools

Javascript minifier

Keep coding guys ! Peace Out ✌