Course contentsShow
← TypeScript
Lesson 1121 of 1,79626. Modules in TypeScriptFree lesson

ESM vs CommonJS Resolution Differences

How module and type: module in package.json affect resolution behavior.

ESM vs CommonJS Resolution Differences

What you'll learn: How module and type: "module" in package.json affect how TypeScript resolves imports and what file extensions are required.

The Tale of Two Module Systems

JavaScript has two competing module systems: CommonJS (the original Node.js system) and ESM (ECMAScript Modules, the standardized version). TypeScript must navigate both worlds, and the resolution rules change depending on which system you're using.

Think of it like choosing between two different postal systems for the same city — each has its own address format and delivery rules.

The module Compiler Option

In your tsconfig.json, the module option tells TypeScript what module output format to generate:

  • "module": "commonjs" — generates require() and module.exports
  • "module": "esnext" or "es2015" — generates import/export statements

This affects how TypeScript compiles your code, but it also influences how it resolves module specifiers when paired with the right moduleResolution setting.

The type: "module" Field in package.json

When you add "type": "module" to your package.json, Node.js treats .js files as ESM rather than CommonJS. This has ripple effects for TypeScript:

Without "type": "module" (CommonJS mode):

  • TypeScript allows extension-less imports
  • Resolution follows Node's traditional algorithm
  • You can mix import and require freely (though not recommended)

With "type": "module" (ESM mode):

  • File extensions become mandatory in relative imports
  • TypeScript enforces ESM-strict rules
  • You must use .js extensions even when importing .ts files (TypeScript will map them)

Key Resolution Differences

In CommonJS mode, this works fine:

import { helper } from './utils'

In ESM mode (with "type": "module"), you must write:

import { helper } from './utils.js'  // .js even for .ts files!

The moduleResolution: "node16" or "nodenext" settings make TypeScript enforce these ESM rules, ensuring your compiled code will actually run in Node.js ESM environments.

Why This Matters

If your module setting and your package.json type field don't align, you'll get confusing errors about missing extensions or incompatible module formats. The resolution strategy must match your runtime environment's expectations.

Key Takeaway: ESM requires explicit file extensions in imports and stricter resolution rules than CommonJS. Configure module, moduleResolution, and package.json type consistently to avoid module resolution errors.