Code Splitting with Parcel Web App Bundler

Written by ankush | Published 2017/12/21
Tech Story Tags: javascript | code-splitting | web-development | parcel-js | javascript-frameworks

TLDRvia the TL;DR App

Code Splitting!! Quite a buzzword in web development nowadays. Today, we will explore code splitting and see how can we do it super easily with parcel.

What is Code Splitting?

If you are already familiar with it… you may skip this part, others, ride along…

If you have done frontend web development with any JavaScript framework, you have surely packed all of your modules into one big bundle JavaScript file, which you attach to your webpage and do amazing stuff. But hey, those bundles are quite big! You have written your awesome(and complicated) web app, with so many parts… they ought to produce big bundles; and bigger the things, longer it takes to download them on slow networks. Ask yourself the question, does the user need all of it at once?

Imagine it’s an e-commerce single page app. The user logs in to see the product listing, he may have come just to check out the products, but he has already spent a lot of time and data not just to download the JavaScript to render the product listing, but also the JavaScript to render about, filters, product detail, offers… and so on and so forth.

By doing this we are doing the users injustice!! Wont it be awesome, if we could give the users what they need,only when they need it?.

So, this idea of splitting your large bundle into multiple smaller bundles is called code splitting. These smaller bundles are loaded on demand and asynchronously. It surely sounds tough to do, but modern bundlers like Webpack make it quite easy, and parcel takes this easiness to whole another level.

The parent is divided into these cute babies. Courtesy Shreya [Instagram]

So, what is this new Parcel thing??

Parcel is the

Blazing fast, zero configuration web application bundler

It makes module bundling really very easy!! If you haven’t heard about it, I recommend this article by Indrek Lasn.

Let’s get Splitting!

To the coding part… I wont use any framework here(which you normally would), but framework or no framework, the process would remain the same. This example would have really really simple code to demonstrate the process.

Create a new empty directory, and init a project, by

npm init

Or,

yarn init

Start it with whatever your favorite is(yarn in my case 😉) and create the files like show below.

World’s simplest file structure

The idea is, we will only include the contents of index.js in our index.html and on an event(it will be a button click in this case) we will load someModule.js and render some content with it.

Open index.html and add the following code.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Code Splitting like Humans</title>

</head>

<body>

<button id="bt">Click</button>

<div class="holder"></div>

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

</body>

</html>

Nothing special, just basic HTML boiler plate, with a button and a div where we will render the content from someModule.js

So, lets write the code for the module someModule

console.log("someModule.js loaded");

module.exports = {

render : function(element){

  element.innerHTML = "You clicked a button";  

}

}

We are exporting an object, which has a function render which takes in an element and sets its inner HTML to “You clicked a button”.

Now, comes the magic. In our index.js file we have to handle the button click event and dynamically load someModule

For the dynamic asynchronous loading we will use the import() function syntax. This function loads a module on demand and asynchronously.

Look at the usage,

import('./path/to/module').then(function(page){

//Do Something});

As import is asynchronous it returns a promise which we handle with then. In then we pass a function which accepts the object loaded from the module. It is similar to const page = require('./path/to/module');, only done dynamically and asynchronously.

In our case,

import('./someModule').then(function (page) {

page.render(document.querySelector(".holder"));

});

We load someModule and call its render function.

Lets add it up inside a button’s click event listener.

console.log("index.js loaded");

window.onload = function(){document.querySelector("#bt").addEventListener('click',function(evt){console.log("Button Clicked");

 import('./someModule').then(function (page) {

     page.render(document.querySelector(".holder"));

 });

});

}

Now that the code is all written, let’s run parcel. Parcel will automatically handle all the configuration work!

parcel index.html

It produces, the following files.

Run it in your browser and observe.

Console output

Network tab

Notice in the console output, someModule is loaded only after the button click. In the network tab see how the module is loaded by codesplit-parcel.js after import function call.

Code Splitting is something awesome, and if it can be done so easily, there is no reason we should step back from it. 💞💞

_Click to see my Youtube channel!!_🤓🤓 I need your love there

Please hit some claps 👏 if you like the content, your support keeps me going. ❤❤


Written by ankush | { Love to code <3 }
Published by HackerNoon on 2017/12/21