Lesson 6 +10 XP

ES Modules (ESM) in Node.js

Modern ES Modules (import / export)

Node.js supports ECMAScript Modules (ESM), which use static analysis and asynchronous loading with import and export statements.

Enabling ES Modules in Node.js

You can enable ES Modules by either:

  1. Setting "type": "module" in your package.json.
  2. Using the .mjs file extension (e.g., server.mjs).

Named and Default Exports

// utils.mjs - Named exports & Default export
export const API_VERSION = "v2";

export function formatUser(name) {
  return name.trim().toUpperCase();
}

export default class ApiClient {
  connect() {
    console.log("Connected to API");
  }
}
// index.mjs - Importing ESM
import ApiClient, { API_VERSION, formatUser } from "./utils.mjs";

const client = new ApiClient();
console.log(API_VERSION, formatUser("  alice  "));

CommonJS vs ES Modules Key Differences

FeatureCommonJS (CJS)ES Modules (ESM)
LoadingSynchronous (require)Asynchronous / Static (import)
Top-Level AsyncNot natively supportedSupported (Top-level await)
Special Vars__dirname, __filename availableUse import.meta.url with fileURLToPath
File ExtensionsRelative paths omit extensionStrict relative path with extension required
// Emulating __dirname in ES Modules
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

TL;DR

  • Set "type": "module" in package.json to use import/export.
  • ESM allows top-level await.
  • Replaces __dirname with import.meta.url.