Loading lesson path
ES Modules (ESM) is the official standard format for packaging JavaScript code for reuse. It was introduced in ES6 (ES2015) and is now supported in Node.js.
Formula
Prior to ES Modules, Node.js exclusively used the CommonJS module format (require/exports).Now developers can choose between CommonJS and ES Modules based on their project needs. ES Modules provides a more structured and statically analyzable way to work with modules compared to CommonJS, with benefits like tree-shaking for smaller builds.
Here's how CommonJS and ES Modules differ:
File Extension.js (default).mjs (or .js with proper config)
import
Formula
Export Syntax module.exports / exports export / export defaultDynamic (runtime) Static (parsed before execution)
// math.js (CommonJS) function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {add, subtract
};
// app.js (CommonJS)
const math = require('./math');
console.log(math.add(5, 3)); // 8// math.mjs (ES Module)
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.mjs (ES Module)
import { add, subtract } from './math.mjs';
console.log(add(5, 3)); // 8There are several ways to enable ES Modules in Node.js:
{Formula
"name": "my - package","version": "1.0.0", "type": "module"
}With this setting, all .js files in your project will be treated as ES Modules.
Formula
3. Using the -- input - type = module Flag
For scripts run directly with the node command, you can specify the module system:
node -- input - type = module script.jsIf you're working with a codebase that primarily uses CommonJS but you want to use ES Modules in one file, using the .mjs extension is the most explicit and least error-prone approach.
ES Modules provide more flexible ways to import and export code compared to CommonJS.
// Multiple named exports export function sayHello() {
console.log('Hello');
}
export function sayGoodbye() {
console.log('Goodbye');
}
// Alternative: export list at the end function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
export { add, subtract };// Only one default export per module export default function() {
console.log('I am the default export');
}
// Or with a named function/class/object function mainFunction() {
return 'Main functionality';
}
export default mainFunction;// Combining default and named exports export const VERSION = '1.0.0';
function main() {
console.log('Main function');
}
export { main as default }; // Alternative way to set default// Import specific named exports import { sayHello, sayGoodbye } from './greetings.mjs';
sayHello(); // Hello
// Rename imports to avoid naming conflicts import { add as sum, subtract as minus } from './math.mjs';
console.log(sum(5, 3)); // 8
// Import all named exports as an object import * as math from './math.mjs';
console.log(math.add(7, 4)); // 11