Module Resolution in TypeScript

1. Welcome and Icebreaker:

  • If you could choose how your mail gets delivered, what would your ideal system be?

2. Outline the Session:

  • We’ll learn how TypeScript finds and resolves modules.
  • Learning Outcomes: Understand how module resolution works and how to configure it.
  • Let’s resolve some mysteries!

3. Concept Explanation:

  • Module Resolution is the process TypeScript uses to find the file for an imported module.
  • There are two main strategies: Classic and Node (default for most projects).
  • TypeScript looks for files in the order: .ts, .tsx, .d.ts, .js, .jsx.
  • You can configure module resolution in tsconfig.json with the moduleResolution option.
  • Path Mapping: Use paths and baseUrl in tsconfig.json to create custom import paths.

4. Live Coding Demonstration:

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@utils/*": ["utils/*"]
    }
  }
}

// Importing with path mapping
import { helper } from '@utils/helper';

5. Tasks:

  • Short Exercise:
    1. Check your project’s tsconfig.json for the moduleResolution setting.
    2. Try changing it and see how it affects imports.
    3. Set up a custom path mapping and use it in an import statement.