Module Bundlers
Learn about the module bundlers and the basic idea of how it works.
We'll cover the following...
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.
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 modulesmoduleA.js
,moduleB.js
, andmoduleC.js
.On the browser: We have
browserApp.js
module, which also importsmoduleA.js
,moduleB.js
, andmoduleC.js
. If our index file were to includebrowserApp.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 preprocessingbrowserApp.js
and all its dependencies and producing a single equivalent bundle called themain.js
module, which is then referenced byindex.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 ...