Advertisement
Beginner TypeScript, Modules

How does TypeScript's import/export syntax relate to the underlying JavaScript module system it compiles to?

Short answer

TypeScript's import/export statements are (mostly) standard ES Module syntax with type-only extensions layered on top; the 'module' compiler option in tsconfig.json controls what actual JavaScript module format (CommonJS, ESNext, ES2020, etc.) this syntax gets compiled down to…

Save TypeScript mock interview
Advertisement
AModel answer
TypeScript's import/export statements are (mostly) standard ES Module syntax with type-only extensions layered on top; the 'module' compiler option in tsconfig.json controls what actual JavaScript module format (CommonJS, ESNext, ES2020, etc.) this syntax gets compiled down to for the target runtime.
// source.ts (ES Module syntax)
export function add(a: number, b: number): number { return a + b; }

// compiled output, if 'module': 'commonjs'
// exports.add = function (a, b) { return a + b; };
Real-world example
Choosing 'commonjs' as the module target for a Node.js backend versus 'esnext' for a modern bundler-based frontend.
Likely follow-ups
  • How do you decide which 'module' setting to use for a given project type?
Related topics