Understanding Modules in JavaScript
Imagine your codebase as a big workshop. Modules are like separate tool-boxes: each holds related tools (functions, variables) and you pull in only what you need. This helps keep things organized, reusable, and easier to manage.
In JavaScript there are two popular “module systems” you’ll encounter:
- CommonJS (CJS)
- ES Modules (ESM)
They both let you split your code into parts, but they work differently. Let’s walk through the differences, and where each fits.
What is CommonJS?
CommonJS is the older system, originally built for server-side JavaScript (especially in Node.js).
Here are its key traits:
- You require modules with
require(…). - You export by assigning to
module.exports(orexports). - Modules are loaded synchronously (at runtime) — meaning the code is executed at the moment the
requirehappens. - It’s dynamic: you can conditionally require modules (inside
if, loops, etc.). - Historically the default in Node-based projects.
Example:
// myModule.js
const value = 42;
module.exports = { value };
// main.js
const myModule = require('./myModule.js');
console.log(myModule.value); // 42Because the loading is synchronous and dynamic, common JS systems tend to work well for server environments where immediate availability is okay.
What are ES Modules?
ES Modules are the newer, standard module system for JavaScript (introduced in ES2015/ES6). They’re designed to work both in browsers and in server environments (with the right setup). Key features:
- Use
import … from …to bring in modules. - Use
export …to export pieces of a module. - Modules are loaded statically, which means imports/exports are known before runtime in many cases.
- Because of the static structure, tools can perform optimizations (like “tree-shaking”, eliminating unused exports).
- In browsers these modules are now natively supported (in modern ones), and in Node.js you can use them with specific configurations (e.g., using
.mjsextension or setting"type": "module"inpackage.json).
Example:
// myModule.js
export const value = 42;
// main.js
import { value } from './myModule.js';
console.log(value); // 42Because of the static design, ES Modules encourage a more declarative structure: “this module exports these, this module imports those” at the top — which can improve readability and tooling.
Side-by-side: CommonJS vs ES Modules
Rather than use a table (Medium doesn’t support tables easily), here’s a bullet style comparison:
Syntax
- CommonJS:
const x = require('…');,module.exports = …. - ES Modules:
import { x } from '…';,export const x = …;.
Loading behaviour
- CommonJS: Modules loaded synchronously at runtime.
- ES Modules: Modules loaded (or at least processed) statically, enabling asynchronous loading in some contexts.
Environment / Compatibility
- CommonJS: Historically built for Node.js (server).
- ES Modules: Designed for both browser and server environments (with configuration).
- In browsers: ES Modules have native support in modern browsers; CommonJS modules typically need bundlers/transpilers.
- In Node.js: You’ll still find lots of CommonJS code; ES Modules are increasingly used.
Optimizations / Tooling
- CommonJS: Because of its dynamic nature (you can require conditionally, export in runtime), tooling such as tree-shaking is more limited.
- ES Modules: Because the exports/imports are known statically (at compile time), bundlers can better optimize — e.g., remove unused exports, make smaller bundles.
File / module naming
- CommonJS: Usually
.jsfiles, and require behaves accordingly. - ES Modules: Often
.mjsextension or.jswith"type": "module"inpackage.json. Also browsers may require full file paths (including extension).
Mixing CommonJS and ES Modules
A lot of older Node.js projects were built using CommonJS, so you’ll still find many libraries that use require() and module.exports.
On the other hand, ES Modules are the modern standard, and most new projects use import and export.
Get Jun Ukemori’s stories in your inbox
Join Medium for free to get updates from this writer.
Because both systems exist side-by-side, you might sometimes work with a mix of them. That’s okay — but it can get a little tricky.
For example:
- A module written with
module.exports = something(CommonJS) doesn’t always behave the same asexport default something(ES Modules). - You might need special syntax or configuration for Node.js to understand which system your file uses — for example, setting
"type": "module"in yourpackage.jsonor using.mjsextensions. - When converting an old CommonJS project to ES Modules, you may need to update import paths or tweak your bundler setup.
In short: it’s possible to mix them, but it’s usually easiest to stick to one module system in your project whenever you can.
When Should You Use Which?
Here are some guidelines (for beginners) to help decide:
- If you’re working in a browser-only context (modern browsers) and you’re starting fresh: go with ES Modules.
- If you’re using Node.js and working with lots of legacy modules (which use
require()): you may stick with CommonJS or gradually migrate to ESM. - If you are building libraries that will be used both in browser and Node, using ES Modules might give you better future-proofing and tooling advantages.
- If you need features like tree-shaking in bundlers (for smaller bundle size): ES Modules are beneficial.
- If you need conditional loading of modules at runtime (depending on logic) and that’s essential: CommonJS supports more dynamic loading.
A Few Gotchas to Watch Out For
- In Node.js, when using ES Modules you might need to set
"type": "module"inpackage.json, or use.mjsfile extensions. - Some libraries export in a format optimized for CommonJS and may require interop layers when used in ES Modules.
- Import paths in ES Modules often must include the full filename (including extension) or correct resolution, especially in browsers.
- With CommonJS you can
requireinside functions/blocks; with ES Modules you cannotimportdynamically in the same way (though dynamicimport()can be used). - Default exports vs named exports can cause confusion when mixing systems: CommonJS
module.exports = somethingmay be imported differently in ESM environments.
The Big Picture
In summary:
- Both systems solve the same high-level problem: modularizing code.
- CommonJS is older, simpler in server contexts, highly used in Node history.
- ES Modules bring in the modern standard, better browser support, static structure, and improved tooling.
- For new projects, leaning into ES Modules is a wise choice; for existing codebases with CommonJS, you may continue or migrate gradually.
Why This Matters for You
As you build JavaScript applications — whether front-end or back-end — you’ll almost certainly need to use modules. Understanding the difference means:
- You can read and understand code that uses either system.
- You can make informed decisions about which module system to use.
- You avoid confusion when your project “just works” in one environment but breaks in another because of module-type mismatches.
- You’ll better understand build-tool configs (like
webpack,rollup,babel, etc.) which often talk about “ESM”, “CommonJS”, “module resolution”, etc.
Final Thoughts
Think of modules as your building blocks. Whether you use CommonJS or ES Modules, the key is to keep your code organized, maintainable, and clear. As JavaScript evolves, ES Modules are becoming the default — so getting comfortable with import/export now will pay off. But knowing CommonJS means you’ll have fewer surprises when working with older code or libraries.
A message from our Founder
Hey, Sunil here. I wanted to take a moment to thank you for reading until the end and for being a part of this community.
Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community. ❤️
If you want to show some love, please take a moment to follow me on LinkedIn, TikTok, Instagram. You can also subscribe to our weekly newsletter.
And before you go, don’t forget to clap and follow the writer️!










