The Civil War: CommonJS vs. ESM

What Is CommonJS (CJS)?

Back in 2009, when Node.js was created to run JavaScript on servers, outside the browsers, the language had a massive flaw: it had no built-in system for sharing code between files.

Get Shreyash’s stories in your inbox

Join Medium for free to get updates from this writer.

So, the Node team created CommonJS (CJS), which gave us module.exports and require().

CommonJS was built specifically for servers. When you run require('./database.js'), Node reads the file directly from your computer’s drive, executes it, and hands you the exported value(s).

Because loading a local file from a hard drive takes mere microseconds, CommonJS is fully synchronous. It blocks execution until the file is loaded, making it simple to write and run line-by-line.

What Is ES Modules (ESM)?

Years later, the official committee that designs JavaScript finally released a global standard: ES Modules (ESM), introducing import and export.

But browser environments are totally different from Node server environments. If a web browser had to synchronously load twenty different JavaScript files over a slow network, the entire page would freeze up while waiting.

Because of this, ESM was designed to be fundamentally asynchronous.

Instead of executing code line-by-line instantly, ESM works in distinct phases. It parses your files, looks at all your import statements, builds a giant dependency tree, allocates memory, and then runs the code. So, all of this takes time which in case of require(), is not allowed.

Because it needs to map your entire application’s structure beforehand, ESM is statically analyzed. You cannot wrap a standard import statement inside an if block.

Similar Posts

Leave a Reply