JavaScript - Part 3: Bundlers and Modules February 11, 2025 on Kenneth Dodrill's blog

Ah, my first delayed post! Sorry for being late. I have been going through some courses to learn more about various web technologies I’m lacking experience with.


Bundlers

Bundlers are tools that transform a point of entry file into (eventually) a JavaScript file that can be consumed by major browsers. Examples of this would be Rollup and Gulp. I have the most experience with Rollup, so I will mostly be using it as an example.

Here’s an example of a project that is using Rollup.

# ...
├── index.html
├── src
│   ├── main.ts
│   ├── ui.ts
│   ├── user.ts
│   └── vector2.ts
└── rollup.config.mjs

Bundlers typically have a configuration file involved so you can change where the point of entry is (or, if there are many).

In this case, main.ts imports and uses other files and is the point of entry. The output goes to ./bundled.js, which the index.html uses.

Notice that the config file has a .mjs file extension. This indicates an ECMAScript module file.

Modules

ECMAScript modules are the official standard format to package JavaScript code for reuse. - nodejs.org

If you have ever seen something like:

// ESM
import * from 'lib';
import { useRef } from 'react';
import Component from './Component';

// Component.js
export default function Component() {}

Then you are seeing ECMAScript modules! Read more about their design.

Alright, so we have a module standard. Great! However, before the standard became, well, standard, NodeJS had their own way of doing things.

// CommonJS
const test = require('./test.js');
const Vector2 = require('./vector2.js');

// vector2.js
module.exports = class Vector2 {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

This type of module is called CommonJS and is still very common today. Many packages still use this module system and therefore your bundler will need to understand it to ensure all your code works and is transpiled correctly.

There is another module type that you might see, although I haven’t really had to deal with it much. See the AMD API documentation.

From what I can see, nowadays most people use ESM (ECMAScript Modules) for the frontend along with a build tool or bundler, and then if you’re building a NodeJS backend use CommonJS.


From this, we learn some things. We knew that just writing JavaScript code is typically not enough, especially if we want to use npm packages. We now know that, without a build tool or bundler, how we use packages and how we write our code doesn’t always translate to a working application.

Again, we find more things that seem to split the JavaScript ecosystem. It should no longer be confusing why learning JavaScript can be so confusing!

Next week I will write a bit on frameworks like React and Vue.js.