Sub topic 2
Choosing the Module Compiler Option
Assume you know basic TypeScript types, import and export, tsc, and package.json. The module option tells TypeScript which JavaScript module format to emit. Choose it based on the runtime that will execute the output.
Match the Target Runtime
For modern Node.js projects, use nodenext. TypeScript then follows Node's rules, including the "type" field in package.json and file extensions. For bundlers, use the bundler's recommended setting, often "module": "esnext" or "preserve".
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"strict": true,
"outDir": "dist"
}
}commonjs emits require and module.exports. Use it when the target runtime expects CommonJS. Avoid mixing formats casually because imports can compile but fail at runtime.
How TypeScript Resolves Imports
Module resolution is the process of finding the file behind an import. With Node-style resolution, TypeScript checks relative paths, package exports, file extensions, and declaration files. In an ESM Node project, write the runtime extension in a relative import even when the source file is .ts:
import { add } from "./math.js";The compiler understands that this refers to math.ts during compilation and math.js after emission.
CommonJS and ES Module Interop
Interop means allowing one module format to consume another. esModuleInterop: true improves compatibility when a CommonJS package is consumed with a default import.
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true
}
}This option affects generated code and type checking. It cannot fix every runtime mismatch, so check how the dependency actually exports its values.
Path Mapping
baseUrl and paths create shorter import names:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@app/*": ["src/*"]
}
}
}Path mappings guide TypeScript's checker, but they do not automatically rewrite JavaScript imports. Configure the bundler or runtime too.
> callout note > Prefer normal relative imports unless your runtime or bundler is configured for path aliases.
Declaration Files
A declaration file, ending in .d.ts, describes types without implementations. It lets TypeScript check JavaScript libraries or published APIs.
// legacy-lib.d.ts
declare module "legacy-lib" {
export function greet(name: string): string;
}With "declaration": true, tsc emits declarations for your exported code. Consumers see signatures, while your implementation stays in .js.
Exercise
Which setting should you investigate first when an import works in TypeScript but fails after compilation?
Show answer
Check module, moduleResolution, and the target runtime's module format and resolution rules.