- read

The Great JavaScript Divide: CommonJS vs ES Modules

Abdelfattah Sekak 46

The Great JavaScript Divide: CommonJS vs ES Modules

It’s time we put an end to this divide and embrace modern and united JavaScript.

Abdelfattah Sekak
JavaScript in Plain English
4 min readSep 21

--

CommonJs vs Es Modules — generate by the author via Midjourney

It’s no secret that the JavaScript community enjoys a good debate. For four years, a partition has lingered over how we should organize our code — a basic yet surprisingly contentious question that continues to divide developers.

This divide surrounds CommonJS and ES Modules, two chief systems for dividing up JavaScript code.

Understanding the split

When JavaScript was initially invented, its primary role was as a scripting language for web browsers. However, with the advent of Node.js, a realm of possibilities seemed to unfurl.

Now, it wasn’t just a language for browsers. It could power servers and other applications alike.

In that scenario, everything in the browser was in the global scope, and you didn’t have to think much about modules. But building a complex server application wasn’t as straightforward. You couldn’t have all your code bundled up in one file — that’d be a nightmare.

The solution that emerged ? A module system called CommonJS.

const moduleA = require('./moduleA');

CommonJS uses a function called require that allows you to pull JavaScript from other files and access functions exported from them.

However, JavaScript soon adapted these ideas with ES6 — the now-famous version — to cater for web applications. They introduced import and export.

import moduleA from './moduleA';

Now, you might wonder, why didn’t JavaScript stick to the require calls already in action?

The issue with require is that it is synchronous and works seamlessly assuming all files are readily available. But, within a browser context, where you might need to wait for external resources, the synchronous nature of require collapses the system.

And thus, the split began.

The compatibility conundrum

A majority of developers moved to ES Modules, as they were not only novel but also enjoyable to use. But a…