Course contentsShow
← TypeScript
Lesson 1626 of 1,79637. Migrating JavaScript to TypeScriptFree lesson

Module Resolution Confusion

Fixing imports that worked in JavaScript but fail in TypeScript due to resolution strategy differences.

Module Resolution Confusion

What you'll learn: How to fix imports that worked perfectly in JavaScript but suddenly fail when you add TypeScript to your project.


The Problem: JavaScript Was Lenient, TypeScript Is Not

In JavaScript, module resolution is handled entirely at runtime by Node.js or your bundler. They're incredibly forgiving—if you write import something from './utils', the runtime happily looks for utils.js, utils/index.js, or even utils.json.

TypeScript performs resolution at compile-time using its own algorithm, which may not match your runtime's behavior. This creates a frustrating gap: imports that work when you run your code can fail during type-checking.

Common Resolution Mismatches

Missing File Extensions

JavaScript (especially with bundlers):

import { helper } from './utils'  // Works fine

TypeScript in strict mode may require:

import { helper } from './utils.js'  // Even for .ts files!

Index File Confusion

Your JavaScript code might import a directory:

import * as api from './api'  // Resolves to ./api/index.js

TypeScript might fail to find it unless moduleResolution is set to "node" or "node16".

Package exports Field

Modern packages use the exports field in package.json. Your bundler respects this, but TypeScript's older resolution modes ("node") ignore it entirely, causing type imports to fail while runtime imports succeed.

The Fix: Align Your Configuration

The key is matching TypeScript's moduleResolution to your actual runtime environment:

  • For Node.js projects: Use "moduleResolution": "node16" or "nodenext"
  • For bundler projects (Webpack, Vite): "moduleResolution": "bundler" (TypeScript 5.0+)
  • Legacy projects: You might need "moduleResolution": "node" temporarily

Also ensure module matches your target ("esnext" for modern bundlers, "commonjs" for older Node).

Key Takeaway: Module resolution confusion happens because TypeScript's compile-time resolver doesn't always match your runtime's behavior—fix it by configuring moduleResolution and module to match your actual execution environment.