Web Development TypeScript Subjective
Oct 04, 2025

Explain the module resolution strategies in TypeScript.

Detailed Explanation
TypeScript supports Node.js and Classic resolution strategies, configurable via moduleResolution option. Node.js Resolution Strategy: // For import { something } from 'moduleA' // TypeScript looks in this order: // 1. node_modules/moduleA/package.json (main field) // 2. node_modules/moduleA/index.ts // 3. node_modules/moduleA/index.tsx // 4. node_modules/moduleA/index.d.ts // 5. node_modules/moduleA/index.js // For relative imports like './utils' // 1. ./utils.ts // 2. ./utils.tsx // 3. ./utils.d.ts // 4. ./utils/package.json (main field) // 5. ./utils/index.ts // 6. ./utils/index.tsx // 7. ./utils/index.d.ts Classic Resolution Strategy: // For import { something } from 'moduleA' // 1. /root/src/moduleA.ts // 2. /root/src/moduleA.d.ts // 3. /root/moduleA.ts // 4. /root/moduleA.d.ts // 5. /moduleA.ts // 6. /moduleA.d.ts Configuration Options: { "compilerOptions": { "moduleResolution": "node", // or "classic" "baseUrl": "./src", "paths": { "@/*": ["./src/*"], "@components/*": ["./src/components/*"], "@utils/*": ["./src/utils/*"] }, "typeRoots": ["./node_modules/@types", "./src/types"], "types": ["node", "jest"] } } Path Mapping: // With baseUrl and paths configuration import { Button } from '@components/Button'; // Resolves to ./src/components/Button import { formatDate } from '@utils/date'; // Resolves to ./src/utils/date Type-Only Imports: // Explicit type-only imports (TypeScript 3.8+) import type { User } from './types/User'; import type * as UserTypes from './types/User'; // Mixed imports import { validateUser, type User } from './user'; Module Augmentation: // Extending existing modules declare module 'express' { interface Request { user?: User; } } Benefits: • Flexible module resolution strategies • Support for path mapping and aliases • Type-only imports for better tree shaking • Compatibility with different environments.
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback