...

/

Module Bundlers

Module Bundlers

Learn about the module bundlers and the basic idea of how it works.

If we want to write large portions of code that can work as seamlessly as possible both on the server and the browser, we need a tool to help us with “bundling” all the dependencies together at build time. These tools are generally called module bundlers. Let’s visualize this with an example of how shared code can be loaded onto the server and the client using a module bundler.

Press + to interact
Loading shared modules on the server and on the browser (using a module bundler)
Loading shared modules on the server and on the browser (using a module bundler)

By looking at the above illustration, we can see that the code is processed and loaded differently on the server side and on the browser: 

  • On the server side: Node.js can directly execute our serverApp.js file, which, in turn, will import the modules moduleA.js, moduleB.js, and moduleC.js

  • On the browser: We have browserApp.js module, which also imports moduleA.js, moduleB.js, and moduleC.js. If our index file were to include browserApp.js directly, we’d have to download a total of five files (index.html, browserApp.js, and the three dependency modules) before the app could be fully initialized. The module bundler allows us to reduce the total number of files to only two by preprocessing browserApp.js and all its dependencies and producing a single equivalent bundle called the main.js module, which is then referenced by index.html and therefore loaded by the browser. 

To summarize: on the browser, we generally have to deal with two logical phases, build and runtime, while on the server, we generally don’t need a build phase and we can execute our source code directly. 

When it comes to picking a module bundler, the most popular option is probably webpack. Webpack is one of the most complete and mature module bundlers currently available and it’s the one we’re going to use. It’s worth mentioning, though, that there’s a really prosperous ecosystem full of ...