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

The --module Flag: Module System Output

Understand how --module determines whether TypeScript outputs CommonJS, ES modules, or other formats.

The --module Flag: Module System Output

What you'll learn: How the --module compiler option controls the format TypeScript uses when generating JavaScript module code.

Why Module Systems Matter

When TypeScript compiles your code, it needs to know how to structure imports and exports in the output JavaScript. Different JavaScript environments expect different module formats—Node.js traditionally uses CommonJS, while modern browsers and bundlers prefer ES modules.

What --module Does

The --module flag tells TypeScript which module system to use when generating JavaScript. This affects how your import and export statements get transformed.

Think of it like choosing a language dialect: Your TypeScript source stays the same, but the "accent" of the output JavaScript changes based on where it needs to run.

Common Values

  • commonjs: Outputs Node.js-style require() and module.exports
  • esnext or es2015, es2020, etc.: Outputs modern import and export statements
  • node16 or nodenext: Hybrid approach matching Node.js's package.json-based module resolution

Practical Impact

When you set "module": "commonjs" in tsconfig.json, your imports become:

const myModule = require('./myModule');

With "module": "esnext", they remain:

import myModule from './myModule';

The choice depends on your runtime environment. Node.js projects often use commonjs, while projects bundled for browsers or using modern Node.js typically prefer ES modules.

Key Takeaway: The --module flag determines the module format of your compiled JavaScript—choose based on where your code will run (Node.js, browsers, or bundlers).