Module Format Configuration with tsc
What You'll Learn
You'll learn how to control the JavaScript module format TypeScript outputs when compiling—determining whether your code becomes CommonJS, ES Modules, or another format.
The Core Idea
When TypeScript compiles your code, it doesn't just strip away types—it can also transform your module syntax into different formats. The module compiler option in tsconfig.json tells tsc which module system to use in the generated JavaScript.
Think of it like a language translator that can output the same message in different dialects. Your TypeScript source stays the same, but the JavaScript output changes to match different runtime environments.
Why This Matters
Different JavaScript runtimes expect different module formats:
- Node.js (older versions) expects CommonJS (
requireandmodule.exports) - Modern browsers and Node.js ESM expect ES Modules (
importandexport) - Legacy environments might need AMD, UMD, or System formats
The module option bridges this gap, letting you write modern TypeScript while targeting the format your runtime needs.
Setting the Module Format
In your tsconfig.json:
{
"compilerOptions": {
"module": "commonjs"
}
}
Common values include:
"commonjs"— Node.js traditional format"esnext"or"es2020"— Modern ES Modules"nodenext"— Hybrid mode for modern Node.js"amd","umd","system"— Specialized formats
The format you choose depends on where your code will run, not how you write it.
Key Takeaway: The module compiler option in tsconfig.json controls what module format tsc outputs—letting you write one codebase that targets different JavaScript runtimes by transforming your imports and exports appropriately.