Topic 28 of 55
import
Overview
ES Modules (ESM) is the official ECMAScript standard for JavaScript modules (using `import`/`export`). Node.js now fully supports ESM, which is asynchronous and aligns Node with modern browser JavaScript.
Syntax
javascript
// To enable ESM in Node.js, you MUST either:
// 1. Add "type": "module" to your package.json OR
// 2. Use the .mjs file extension.
// --- math.mjs (Exporting) ---
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;
export default function multiply(a, b) {
return a * b;
}
// --- app.mjs (Importing) ---
// In Node.js ESM, you MUST include the file extension!
import multiply, { add, PI } from './math.mjs';
console.log(multiply(add(2, 3), 2)); // 10Common Pitfalls
- Unlike CommonJS, Node.js ESM requires the full file extension when importing local files (e.g., `import './config.js'`, not `import './config'`).
- In ESM, pseudo-globals like `__dirname` and `__filename` do NOT exist. You have to reconstruct them using `import.meta.url`.
Real-World Example
Using Top-Level Await (only available in ES Modules):
example
javascript
// Because ESM is asynchronous, you can use 'await' at the top level
// of a file without wrapping it in an async function!
import fetch from 'node-fetch';
// This blocks the execution of THIS module until the fetch completes
const res = await fetch('https://api.github.com/users/github');
const data = await res.json();
console.log(data.name);
export const githubData = data;