How Does Module Resolution Work in TypeScript?

Learn How Does Module Resolution Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Module Resolution

TypeScript applications commonly consist of multiple files, libraries, and reusable modules. When a source file imports a function, class, interface, or package, TypeScript must determine where the imported declaration comes from and how to obtain the corresponding type information.

Module resolution is the process TypeScript uses to interpret an import path and locate the appropriate module. Depending on the project, the target may be a TypeScript file, a JavaScript file, a declaration file, or an entry point exposed by an installed package.

Understanding module resolution helps developers diagnose errors such as Cannot find module, missing type declarations, incorrect package imports, and differences between editor checks and runtime behavior. It is especially important in projects that use Node.js, modern JavaScript modules, Angular, React, or a bundler.

1. How Module Resolution Works

Whenever TypeScript encounters an import, it attempts to resolve the specified path according to the active module-resolution strategy. That strategy determines which locations, file extensions, package metadata, and directory conventions TypeScript considers.

// src/utils/format.ts

export function formatName(name: string): string {
  return name.trim().toUpperCase();
}
// src/app.ts

import { formatName } from "./utils/format";

console.log(formatName("TypeScript"));

TypeScript resolves the relative import from the importing file and looks for a compatible module according to the configured strategy. In this example, the intended source is format.ts.

Resolving a module involves more than finding a file with a similar name. TypeScript may also need to identify the declaration that describes a JavaScript package, interpret package.json metadata, or follow conditional exports.

Successful type-level resolution does not always guarantee that the application can load the module at runtime. TypeScript, a bundler, and Node.js may apply different rules, so their configurations must be compatible.

2. Understanding module and moduleResolution

Two compiler options are particularly important when configuring modules: module and moduleResolution. Although they are related, they control different aspects of the module system.

module

Controls the module format TypeScript uses when generating JavaScript and affects how module syntax is interpreted. For projects that use noEmit and a separate build tool, it still influences module-related checking and compatibility.

moduleResolution

Controls how TypeScript locates modules and their declarations. It determines which file paths, package metadata, and resolution rules are considered when processing imports.

A bundler-based application might use a configuration similar to this:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "noEmit": true
  },
  "include": ["src/**/*"]
}

This is an illustrative configuration for a project where a bundler handles application output. The ESNext module setting preserves modern module syntax for the surrounding toolchain, while Bundler resolution follows rules designed for bundler-based workflows.

The noEmit option prevents TypeScript from generating output files. Remove or adjust it if the project relies on the TypeScript compiler to emit JavaScript.

3. Choosing a Module Resolution Strategy

TypeScript provides different module-resolution strategies for different environments. The correct choice depends on how the application is executed and how its dependencies are loaded.

Strategy Typical use
Bundler Applications processed by bundlers such as Vite, webpack, or similar tools that support modern module resolution.
NodeNext Node.js projects that use modern ECMAScript modules and CommonJS according to Node.js package rules.
Node16 Projects targeting Node.js 16-style module resolution and package semantics.
Node10 Legacy Node.js-style resolution used by older projects. It does not model modern Node.js package exports in the same way as NodeNext.

The Node16 and NodeNext strategies model Node.js's runtime module behavior, including distinctions between CommonJS and ECMAScript modules. NodeNext tracks the evolving Node.js module system, while Node16 targets the corresponding Node.js 16-era rules.

Bundler is designed for applications whose imports are processed by a bundler. It permits certain import patterns that Node.js would not necessarily resolve directly at runtime.

The older node10 setting is intended for legacy resolution scenarios rather than new projects that depend on modern Node.js package behavior. Choose the strategy that matches the actual runtime and build pipeline instead of selecting one solely because an import appears to work in the editor.

4. Resolving Relative Module Imports

Relative imports begin with ./ or ../. They identify files or directories relative to the importing module, making them useful for organizing code within an application.

src/
  app.ts
  utils/
    format.ts
  services/
    course-service.ts
// src/app.ts

import { formatName } from "./utils/format";
import { getCourse } from "./services/course-service";

The ./ prefix refers to the current directory, while ../ moves to the parent directory. TypeScript uses the importing file's location as the starting point when resolving these paths.

Under a bundler-oriented strategy, file extensions can often be omitted for supported source imports. Under NodeNext or Node16, relative import extensions must generally follow the emitted runtime module format. For example, an ESM TypeScript source file might import a sibling module using a .js extension because that is the extension of the generated JavaScript file.

// Example for Node.js ESM with NodeNext

import { formatName } from "./utils/format.js";

The .js extension in that example does not mean the source file must be written in JavaScript. Under the appropriate TypeScript and Node.js configuration, TypeScript can resolve the import to the corresponding format.ts source file while preserving the .js specifier for runtime use.

Always follow the conventions of the project's selected module system. Do not add or remove extensions blindly, because a path accepted by one build tool might be invalid for another runtime.

5. Resolving Package Imports

Package imports refer to dependencies installed through a package manager. They generally use the package name rather than a relative file path.

import { useState } from "react";
import { format } from "date-fns";

TypeScript searches for the package according to the configured resolution strategy. Depending on the package and strategy, it may examine the package's package.json file, exported entry points, type declarations, and other supported metadata.

Packages may provide TypeScript declarations in their own distribution, or use separate declaration packages. A package's JavaScript implementation and its type declarations serve different purposes: JavaScript supplies runtime behavior, while declarations describe the public API for static checking.

If a package cannot be resolved, verify that it is installed in the correct project, that its import path is supported by the package, and that the selected module-resolution strategy recognizes its package structure.

6. How package.json Influences Resolution

Package metadata helps define how applications and TypeScript locate a library's public entry points. Modern packages can use fields such as exports, types, and type to describe their supported entry points and type declarations.

{
  "name": "course-utils",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    }
  }
}

This simplified example describes an ECMAScript module package with a public root entry point and a corresponding declaration file. Actual package configurations may include additional conditions, CommonJS entry points, development conditions, or subpath exports.

The exports field defines which package entry points consumers may access. When a package defines exports, consumers generally cannot import arbitrary internal files unless those paths are explicitly exposed.

The types or type field can indicate the package's TypeScript declaration entry point. Modern package exports can also provide a types condition for declarations associated with a particular entry point.

A package may work with one resolution strategy and fail with another if its metadata relies on modern exports or conditional entry points. When publishing libraries, make sure the package metadata describes the runtime files and declaration files actually included in the published package.

7. Understanding Declaration Files

Declaration files use the .d.ts extension and describe types without containing the corresponding runtime implementation. TypeScript can use declarations to check calls to JavaScript libraries and other modules.

// math-utils.js

export function add(first, second) {
  return first + second;
}
// math-utils.d.ts

export declare function add(
  first: number,
  second: number
): number;

The declaration tells TypeScript that add accepts two numbers and returns a number. The JavaScript file contains the actual implementation that runs when the function is called.

When resolving a JavaScript module, TypeScript may locate a corresponding declaration file to obtain more precise type information. If no suitable declaration is available, it may infer types from the JavaScript source or report that type declarations could not be found.

Incorrect declarations can produce misleading compiler results. Keep declaration files consistent with the real implementation, and avoid describing a runtime API that the package does not actually provide.

8. Using paths and baseUrl for Aliases

Large applications can develop long relative import paths when files are nested deeply. TypeScript supports path mapping through the paths compiler option, which allows developers to define convenient aliases for selected module locations.

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

These aliases can then appear in imports:

import type { Course } from "@models/course";
import { getCourse } from "@services/course-service";
import { formatName } from "@utils/format";

The paths setting tells TypeScript how to resolve the aliases during type checking. It does not generally rewrite the import specifiers into relative paths in emitted JavaScript.

Your bundler, runtime, or other tooling must understand the same aliases when necessary. If TypeScript accepts an alias but the application fails at runtime, compare the path mappings used by the compiler with the configuration used by the actual loader.

Modern TypeScript projects may use other aliasing mechanisms as well, including package imports defined through package.json. Select the mechanism supported by your runtime and build tools, especially when code must run directly in Node.js without bundling.

9. NodeNext and Node.js ESM Resolution

Node.js supports both CommonJS and ECMAScript modules, and the module format of a file affects how its imports are interpreted. TypeScript's NodeNext and Node16 strategies model Node.js module resolution rules more closely than bundler-oriented resolution.

A Node.js project using modern ECMAScript modules may use a configuration similar to this:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"]
}

Under NodeNext, the compiler considers how Node.js interprets individual files. A package.json file with type set to module generally establishes ECMAScript module semantics for applicable .js files, while .cjs and .mjs extensions explicitly identify CommonJS and ECMAScript module formats.

TypeScript source files also need to be interpreted consistently with their eventual runtime output. In Node.js ESM source, relative import specifiers generally use the extension of the emitted JavaScript file rather than an arbitrary extensionless path.

// src/app.ts
import { formatName } from "./format.js";

// src/format.ts
export function formatName(name: string): string {
  return name.trim();
}

In a compatible NodeNext configuration, TypeScript can resolve the .js import to format.ts during compilation and retain the runtime-compatible specifier in the emitted JavaScript.

Module behavior depends on the project's package metadata and file extensions. Review the Node.js module rules and TypeScript configuration together rather than copying an ESM example directly into a CommonJS project.

10. Package Exports and Subpath Imports

The exports field in package.json allows a package to define which public entry points consumers may import. It can expose a root entry point as well as selected subpaths.

{
  "name": "course-utils",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    },
    "./format": {
      "types": "./dist/format.d.ts",
      "import": "./dist/format.js"
    }
  }
}

Consumers can then import the root package or its public format subpath:

import { getCourses } from "course-utils";
import { formatName } from "course-utils/format";

The package defines its public interface explicitly instead of exposing every file in its directory. This makes it easier to change internal organization while keeping supported imports stable.

Conditional exports can select different entry points depending on the environment or resolution condition. A complete package may therefore need distinct entries for ESM, CommonJS, and type declarations.

If TypeScript resolves a path that the runtime rejects, inspect the package's exports field and confirm that the imported subpath is actually public. Avoid depending on internal package files that are not part of the supported API.

11. Using Trace Resolution to Debug Imports

When an import cannot be resolved, guessing at configuration changes can make the project more difficult to maintain. TypeScript provides trace-resolution diagnostics to show how the compiler attempts to locate imported modules.

npx tsc --noEmit --traceResolution

This command runs the compiler with detailed module-resolution output. The trace can show the import being processed, candidate file paths, package.json files examined, and whether a declaration or source file was successfully located.

Trace output can be lengthy in a large project. To make it easier to investigate, start by identifying the unresolved import and looking for the corresponding section of the trace.

Combine trace output with checks of the actual filesystem, package installation, compiler configuration, and runtime module rules. A successful TypeScript resolution trace does not prove that Node.js or a bundler will load the same import successfully.

12. Common Module Resolution Errors

Cannot find module

Check the path, filename capitalization, installed dependency, included source directories, and module-resolution configuration. Verify whether the import is supported by the selected runtime or build tool.

Cannot find declaration files

Confirm whether the package includes types or whether a compatible declaration package exists. You may need a declaration file for an otherwise valid JavaScript dependency.

An import works in the editor but fails at runtime

The TypeScript compiler and runtime may use different resolution rules. Check the emitted import path, file extensions, bundler aliases, and package exports.

Package subpath is not exported

A package with an exports field restricts which subpaths can be imported. Use a supported public entry point or change the package's public exports if you control the package.

Extension errors with Node.js ESM

Node.js ESM commonly requires explicit extensions for relative runtime imports. Review the emitted JavaScript paths and use a compatible NodeNext or Node16 configuration when appropriate.

Path alias resolves only in TypeScript

A paths mapping informs TypeScript's resolver but does not generally rewrite emitted import specifiers. Configure the relevant runtime, bundler, and test tools to support the alias.

Best Practices for Module Resolution

  • Choose moduleResolution according to the actual runtime and build pipeline.
  • Keep module and moduleResolution settings compatible with one another.
  • Use relative imports for nearby application files and package imports for installed dependencies.
  • Follow the appropriate file-extension rules for your selected Node.js or bundler environment.
  • Use paths aliases only when the runtime and build tooling support the same mappings.
  • Keep package exports and declaration entry points aligned with the files included in the published package.
  • Use declaration files to describe JavaScript libraries that lack appropriate type information.
  • Use trace-resolution diagnostics when an import cannot be located instead of making random configuration changes.
  • Test the actual production build and runtime because successful editor resolution alone is not sufficient.

Conclusion

TypeScript module resolution determines how imported declarations are located and connected to source files, declaration files, and installed packages. The moduleResolution option selects the rules used by the compiler, while package metadata, file paths, extensions, and declaration files help determine the actual module entry point.

For reliable applications, select a resolution strategy that matches the runtime, understand the difference between compiler aliases and runtime paths, and use trace-resolution output to investigate difficult imports. These practices help prevent configuration errors and make TypeScript projects easier to build, debug, and maintain.

Code Examples

Resolving a Relative Import

typescript
// utils/format.ts
export function formatName(name: string): string {
  return name.trim().toUpperCase();
}

// app.ts
import { formatName } from "./utils/format";

console.log(formatName("TypeScript"));
    

A relative import identifies a module based on the location of the importing file. The exact extension rules depend on the configured runtime and resolution strategy.

Configuring Bundler Resolution

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "noEmit": true
  },
  "include": ["src/**/*"]
}
    

This example is intended for a bundler-based project. The bundler is responsible for generating application output, so TypeScript does not emit JavaScript files.

Configuring NodeNext Resolution

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"]
}
    

NodeNext models modern Node.js module resolution and module-format rules. The package metadata, file extensions, and runtime must agree with the selected configuration.

Configuring Path Aliases

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

Path mappings allow TypeScript to resolve shorter import aliases. Configure the bundler, runtime, or test environment as well when it must resolve those aliases.

Resolving a Package with Declaration Files

typescript
// math-utils.d.ts
export declare function add(
  first: number,
  second: number
): number;

// math-utils.js
export function add(first, second) {
  return first + second;
}

// consumer.ts
import { add } from "./math-utils";

const total = add(10, 20);

console.log(total);
    

The declaration file describes the JavaScript module's public type signature, allowing TypeScript to check the imported function while the JavaScript file provides its runtime implementation.

Debugging Module Resolution

json
// package.json
{
  "scripts": {
    "typecheck": "tsc --noEmit",
    "trace-modules": "tsc --noEmit --traceResolution"
  }
}

// Run from the terminal:
// npm run typecheck
// npm run trace-modules
    

The traceResolution option prints detailed information about how TypeScript attempts to resolve imports. Use the output to investigate missing modules and incompatible package metadata.

Pro Tip

Choose moduleResolution based on where your code will actually run. Use Bundler for compatible bundler-based applications and NodeNext for modern Node.js projects. Remember that paths aliases do not generally rewrite emitted imports, and use npx tsc --noEmit --traceResolution when you need to understand why TypeScript cannot locate a module.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.