Back to Blog Listing

ES Modules vs. CommonJS: The JS Module System

JavaScript modules allow developers to break up codebases into reusable, self-contained files. Historically, the language had no native module syntax, which led to the creation of **CommonJS** for Node.js and eventually **ES Modules** as the official standard.

CommonJS (CJS)

CommonJS uses require() to load modules synchronously and module.exports to export. It is the default in older Node.js environments.

// math.js
module.exports.add = (a, b) => a + b;

// index.js
const { add } = require('./math');

ES Modules (ESM)

ES Modules are the official standard. They use import and export and operate asynchronously, enabling static analysis and optimizations like tree-shaking (removing unused code during build).

// math.js
export const add = (a, b) => a + b;

// index.js
import { add } from './math.js';
💻

Try this code in our online compiler!

Don't just read about it. Write, run, and experiment with these JavaScript concepts instantly on our online workspace with autocomplete suggestions.

Share this tutorial:

CodeCompile