CommonJS and ESM are two ways to organize and share code in Node.js. They help your code talk to other files or libraries.
0
0
CommonJS vs ESM differences in Node.js
Introduction
When you want to include code from another file in your project.
When you use third-party libraries that use either CommonJS or ESM format.
When you want to write modern JavaScript that works with import/export.
When you need compatibility with older Node.js versions or tools.
When you want to optimize loading and performance with static imports.
Syntax
Node.js
CommonJS: const module = require('module') module.exports = value ESM: import module from 'module' export default value
CommonJS uses require() and module.exports.
ESM uses import and export keywords.
Examples
CommonJS example: load file system module and export data.
Node.js
const fs = require('fs') const data = fs.readFileSync('file.txt', 'utf8') module.exports = data
ESM example: import file system module and export data as default.
Node.js
import fs from 'fs' const data = fs.readFileSync('file.txt', 'utf8') export default data
CommonJS exports an object with a function.
Node.js
const add = (a, b) => a + b
module.exports = { add }ESM exports a named function directly.
Node.js
export function add(a, b) {
return a + b
}Sample Program
This shows a CommonJS module exporting a function, and an ESM module importing and using it.
Note: Node.js requires special setup to mix CommonJS and ESM files.
Node.js
// CommonJS module: math.js
const multiply = (x, y) => x * y
module.exports = { multiply }
// ESM module: main.mjs
import { multiply } from './math.js'
console.log(multiply(3, 4))OutputSuccess
Important Notes
CommonJS loads modules synchronously, ESM loads them asynchronously.
ESM supports static analysis and tree shaking for smaller bundles.
Node.js treats files with .mjs as ESM and .cjs as CommonJS by default.
Summary
CommonJS uses require and module.exports, ESM uses import and export.
ESM is the modern standard and supports better optimization.
Choose based on your project needs and Node.js version compatibility.