09 - Modules: ESM and CJS
📋 Jump to Takeaways🎁 import and require aren't just two syntaxes for the same thing. They're two different module systems with different rules — and mixing them is one of the most common sources of "it works locally but breaks in prod" in Node.js.
Two module systems. Not by design. Node.js shipped CommonJS (CJS) in 2009, then the ES standard added ESM later. Now both exist.
You write ESM. You read CJS when you hit older packages. That's it.
ESM: What You Write
Named Exports
Export individual values by name.
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14159;// main.ts
import { add, PI } from "./math.js";
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159Notice the .js extension in the import. TypeScript compiles .ts to .js, so your imports reference the output file. This trips up everyone at first.
Default Exports
One default export per file. Use it for the "main thing" a module provides.
// logger.ts
export default class Logger {
log(msg: string): void {
console.log(`[LOG] ${msg}`);
}
}// main.ts
import Logger from "./logger.js";
const logger = new Logger();
logger.log("started"); // [LOG] startedYou can name the default import anything. That's the problem. Named exports are greppable. Default exports are not. Use named exports.
Re-exports
Pull things from one module and export them from another.
// utils/index.ts
export { add, PI } from "./math.js";
export { default as Logger } from "./logger.js";
export type { Config } from "./config.js";// main.ts
import { add, Logger } from "./utils/index.js";export type tells TypeScript this export is types only. It gets erased at compile time. Use it for interfaces and type aliases.
CJS: What You Read
You won't write CJS, but you'll see it in older packages and Stack Overflow answers.
// CJS style - recognize it, don't write it
const express = require("express");
module.exports = { handler };
module.exports.default = app;The equivalent ESM:
// ESM style - write this
import express from "express";
export { handler };
export default app;When you see require() in docs or examples, translate it to import in your head.
Interop: Where Things Get Weird
Importing a CJS module from ESM usually works. Usually.
// CJS module exports: module.exports = { foo: 1, bar: 2 }
// This works:
import pkg from "some-cjs-package";
console.log(pkg.foo); // 1
// This might NOT work (depends on the package):
import { foo } from "some-cjs-package";
// Could error: SyntaxError: Named export 'foo' not foundCJS modules export a single object. ESM named imports try to destructure that object. Node.js does some magic to make this work for many packages, but not all.
Safe pattern: import the default, then destructure.
import pkg from "some-cjs-package";
const { foo, bar } = pkg;The esModuleInterop Fix
In your tsconfig.json:
{
"compilerOptions": {
"esModuleInterop": true
}
}This lets you write import express from "express" instead of import * as express from "express". Always turn it on.
Barrel Files
A barrel file is an index.ts that re-exports from other files. It creates a clean public API.
// lib/index.ts
export { UserService } from "./user-service.js";
export { AuthService } from "./auth-service.js";
export type { User, Session } from "./types.js";// Consumers get a clean import
import { UserService, AuthService } from "./lib/index.js";When Barrels Hurt
Barrel files cause two problems.
Tree shaking failure. Import one thing from a barrel, and bundlers might pull in everything the barrel re-exports. Less of an issue on the backend, but it still bloats your build.
Circular dependencies. Module A imports from the barrel. The barrel re-exports Module B. Module B imports from Module A. Cycle. Things break at runtime with mysterious undefined values.
// This creates a cycle:
// lib/index.ts re-exports both user.ts and auth.ts
// user.ts imports { AuthService } from "./index.js"
// auth.ts imports { UserService } from "./index.js"
// Fix: import directly, skip the barrel
import { AuthService } from "./auth-service.js";Use barrels at package boundaries. Don't use them for internal imports within the same package.
Path Aliases
Tired of ../../../lib/utils? Set up path aliases in tsconfig.json.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}Now you write:
import { UserService } from "@/services/user-service.js";
// Instead of:
import { UserService } from "../../../services/user-service.js";One catch. TypeScript resolves these at compile time, but Node.js doesn't know about them at runtime. You need a runtime resolver too. Bundlers (esbuild, Vite) handle it natively. tsx does not resolve path aliases by default — you need tsconfig-paths or a similar plugin. Raw node does not support them either.
package.json "type": "module"
This one field changes how Node.js treats your .js files.
{
"type": "module"
}Without it, Node treats .js files as CJS. With it, Node treats .js files as ESM. For new TypeScript projects, always set this.
{
"name": "my-backend",
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
}If you forget "type": "module" and your compiled JS uses import/export, Node throws:
SyntaxError: Cannot use import statement outside a moduleYou'll see this error at least once. Now you know the fix.
Key Takeaways
- Write ESM (
import/export). Read CJS (require/module.exports) when you encounter it in older code. - Use named exports over default exports. They're greppable and refactor-friendly.
- Set
"type": "module"inpackage.jsonand"esModuleInterop": trueintsconfig.json. - Use barrel files at package boundaries, not for internal imports. They cause circular dependency headaches.
- Path aliases clean up imports but need runtime support beyond just
tsconfig.json. - When importing CJS from ESM, import the default and destructure. Named imports from CJS are unreliable.
🎁 Go's compiler refuses to build if you ignore an error. TypeScript's doesn't — the catch variable is unknown, errors aren't checked at compile time, and an unhandled rejection crashes your process. How do you get Go-style error safety in a language that doesn't enforce it?