Course contentsShow
← TypeScript
Lesson 53 of 1,7962. Setup and ToolingFree lesson

module: Selecting Your Module System

Configuring the module code generation (CommonJS, ES2015, ESNext, Node16) to match your runtime environment.

module: Selecting Your Module System

What You'll Learn

You'll learn how to configure TypeScript's module compiler option to match the module system your JavaScript runtime expects.

The Core Idea

When TypeScript compiles your code to JavaScript, it needs to know how to handle imports and exports. Different JavaScript environments understand different module formats. The module option in tsconfig.json tells TypeScript which format to output.

Think of it like choosing the right plug adapter for traveling abroad—your code (the device) works fine, but you need the right format (plug type) for where it's going to run (the country).

Common Module Options

"commonjs" — The traditional Node.js format using require() and module.exports. Use this for older Node.js projects or tools that haven't adopted ES modules.

"es2015" / "esnext" — Modern ES module format using import and export. Use this for modern browsers or bundlers like webpack and Rollup that understand ES modules.

"node16" — Node.js 16+ hybrid system that respects package.json's "type" field. Use this for modern Node.js projects that support both CommonJS and ES modules.

Matching Your Environment

Your choice depends on where your compiled JavaScript will run:

  • Building a library for npm? Check what your users expect.
  • Running in Node.js? Match your Node version's capabilities.
  • Bundling for browsers? Your bundler (covered by target) likely prefers "esnext".

In your tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs"
  }
}

Key Takeaway: The module option determines how TypeScript translates your import/export statements into JavaScript module syntax—choose the format that matches your runtime environment.