ES Modules (ESM) is the official JavaScript module system. It uses import and export instead of require(). Node.js has supported ESM since version 12.
How to Enable ES Modules
You have two options:
// Option 1: Add "type": "module" to package.json
{
"type": "module"
}
// Option 2: Use .mjs file extension
// math.mjs
Exporting with ES Modules
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export const PI = 3.14159;
// Default export
export default function multiply(a, b) {
return a * b;
}
Importing with ES Modules
// app.js
import multiply, { add, subtract, PI } from "./math.js";
console.log(add(2, 3)); // 5
console.log(multiply(4, 5)); // 20
console.log(PI); // 3.14159
// Import everything as namespace
import * as math from "./math.js";
console.log(math.add(1, 2));
Dynamic Imports
You can import modules conditionally or lazily:
// Load module only when needed
if (needsHeavyModule) {
const heavy = await import("./heavy-module.js");
heavy.process();
}
// In async function
async function loadData() {
const { parse } = await import("csv-parse/sync");
const data = parse(csvString);
}
Try it Yourself →
CommonJS vs ES Modules
// CommonJS
const { add } = require("./math.js");
// ES Modules
import { add } from "./math.js";
// CommonJS
module.exports = { add };
// ES Modules
export { add };
Important: You cannot mix CommonJS and ES Modules in the same file. Choose one and stick with it. Most new Node.js projects use ES Modules.