Are you an aspiring JavaScript Developer? Have you been writing JavaScript for a while but lack confidence when talking about modules? Have you run across terms like "module loaders" and "module bundlers" and wondered what they mean? Have you heard about webpack, Browserify, CommonJS, and AMD and not understood why we use these things? Follow this three-part series to learn more! 

The adventure begins with some history on the need for modules and why so many tools were then created to work with them. So have you got your coffee mug? Then come on! It will be a long story.

Table of Contents

Part I: The Beginning

The Origin

Breaking the Code

New Problems Arise

Part 2: Exploring Solutions

The First Script

A First Approach to Modules

The Second Script

His Own Bundler

Part 3: Holy Tools

Generated Code

Webpack and JavaScript

Afterword

Part I: The Beginning

Preamble: Inline Script

There's no better place to start than with this oft-heard term! Inline Script brings back good memories of how I wrote my first web applications. Inline Script is when you add scripts directly to your page, inside an HTML tag called <script>. That's how I started, and I think most other developers probably start there too.

It's a good way to begin coding quickly, to be honest. There are no files or external dependencies to worry about, but on the other hand, it's a perfect recipe for hard-to-maintain code over, and there are some reasons for that! These reasons include:

1. Lack of code reusability: If you need to add a page to your website that will also include some function or feature of another page you already have, you will need to copy and paste that code.

2. Lack of dependency resolution: Depending on the way you write your script, you will be responsible for organizing the functions in a specific order so that they will already exist at the time they are used.

3. Global scope pollution: All functions and variables will live within the overall scope of your application. Later on, you will understand the problem with this.

Although I'm not going to explore the nitty gritty details of Inline Script in the history that follows, I could not neglect mentioning this subject entirely. We can now begin our story, having established why the use of Inline Script introduces certain problems (and by the way, these problems also apply to Inline Style!).

Chapter I: The Origin

Scene: a young programmer who owns a single script of 500 lines of code, a script written with a lot of dedication to the web page he is working on. It is composed in an epic language of unimaginable features (whose witchcraft is incredible) called JavaScript. Jay Ess is his name, and his life is a very good life. His script was, in the beginning, very handy and of reasonable size.

But time is said to be cruel to some, and it was no different with Jay Ess. With the passing days, the project on which he worked day-to-day grew, and in that flow of growth he began to add more features to his page. Not only that, but he became a team member because his company hired new developers to work with him on that same web page.

If Jay Ess continues with his current configuration (a single script file to which he and possibly "others" might start adding new features), he will encounter two problems on his journey:

1. His script file will grow. It will grow like the chuchu vegetable in the fence (those who come from the countryside know this expression). That is, it will grow very fast with each new functionality. This is bad because large files are difficult to maintain, and we know that it's complicated to find specific sections. Beyond this, we also know that it's difficult to have multiple developers working on the same file at the same time.

2. One day, Jay Ess may want to use some external libraries. While not technically a problem, this could further complicate the situation.

Chapter II: Breaking the Code

With this problem troubling his mind, Jay Ess uses his incredible acumen and obviously decides to break this huge script file into several smaller files. He does this not only because the file is large, but also because it's good practice to separate things into independent parts to keep the code organized and clean, right? This is even justifiable since developers may want to separate functions that handle DOM manipulation from other functions that handle http requests or data processing, etc.

Let's say Jay Ess eventually had a file size of 10KLOC, and in his above-mentioned change, he quickly broke the file into smaller pieces, getting 20 smaller script files, sizing 500LOC each. The result is neither great nor wonderful, but it's definitely better. (KLOC = 1,000 lines of code [k = 1,000; LOC = lines of code].)

But what is Jay Ess's plan for managing these files? He concludes that the simplest solution is to put 20 <script> tags on his page, or maybe 20 other tags for the libraries that he added throughout this process, such as lodash, jQuery (just to keep up the drama), and other plugins.

Yet Jay Ess still faces a significant challenge: maintaining order. He has to be careful when inserting tags to make sure that some things (such as utility functions) will be available before other parties use them.

Jay Ess's life has improved in some ways: he has smaller files, which help in his day-to-day work routine. But things are not all moonlight and roses, you know. This poor guy added some brand new concerns, and these are concerns he needs to address right away.

Not only does he have to track the order of his <script> tags, but when his team members add new functions, they also have to decide where to place them. How should they store files so that they will be available when called for? Is it better to add a new file and a new <script> tag?

Jay Ess is deep in thought as he opens a package of Doritos…

Also, now that he understands the importance of separation of responsibilities (the first of the SOLID principles he studied in college once upon a time), he is producing a larger number of small files that he’ll have to organize into folders. Quickly his web app reaches 50, 80, 100... JavaScript files. Just as Jay Ess can see that his code is more stable, so we too, as spectators, can see new problems emerging.

Chapter III: New Problems Arise

Jay Ess was already worried about the number of <script> tags he has produced and the order he has to maintain ... and now a new challenge emerges. His files define multiple names, such as function names, variable names, etc. And every time he chooses to change some file, he has no idea what names the other files have already declared. Collisions could happen! Development becomes a tedious task-- he has to remember several names that have been used before or keep looking for some convention, or ... well, you get the idea. Now he has a new problem to solve.

Seeking the wisdom to solve his problem, desperately searching for tutorials, books, reddit and everything else, Jay Ess finally discovers the so-called Module Patterns:

let something = (() => {

    // so called "encapsulation" here

    // ...

    // and then...

    return {

        firstPublic: ...,

        second public: ...

    };

}) ();

Basically, this pattern allows developers, through the use of closures, to encapsulate code. The thing returned and assigned to some of the above has methods and properties visible, and these methods have access to local things defined within the expression of the function, to which no one outside it has access. So, in a way, it's this structure that can allow Jay Ess to write encapsulated blocks of code with private visibility. But why is this relevant to him?

This can help him avoid his problem with name collisions. Aha! (If you have not perused the information in the link above, I highly recommend doing so if you still do not know what this means.) So what Jay Ess decides to do is create this structure in each of those 80, 100 ... files he has, swallowing the entire contents of each file. And in the end, this structure will return only the things that he really wants to be visible.

That is a huge gain: Jay Ess can break files into smaller files without worrying about name collisions. On the other hand, he has 180 <script> tags or even more than that on his page. And you remember that concern about the order of the files? This is still a problem, but it's a problem that will remain unaddressed until next week’s installment of A Web History: The Origin of Bundlers!


Author

Igor Rezende

Igor Octaviano is a UI Engineer at Avenue Code. He is a web developer, consultant, writer, musician, sometimes MMORPG enthusiast who values learning and teamwork when designing and developing applications.