Browse topics

TypeScript module resolution

Version
es2025
Since
4.7
Review
Draft

Summary#

moduleResolution controls how TypeScript locates files for imports. Match this setting to the tool that will load the code. Use nodenext for direct execution of emitted files in modern Node.js. Use bundler when your bundler supports its lookup rules.

Syntax#

sh
tsc --module nodenext --noEmit
tsc --module esnext --moduleResolution bundler --noEmit

These commands check the current TypeScript project. --module nodenext selects nodenext resolution automatically.

Example#

Run this shell example with Node.js and your project's TypeScript compiler (tsc) on your path.

sh
(
  set -eu
  work_dir=$(mktemp -d "${TMPDIR:-/tmp}/dlr-js-ts-core-XXXXXXXX")
  trap 'rm -rf -- "$work_dir"' 0
  trap 'exit 1' HUP INT TERM
  cd "$work_dir"
  export TMPDIR="$PWD"
  unset NODE_COMPILE_CACHE

  cat > fares.mts <<'TS'
export const fare = 4;
TS

  cat > receipt.mts <<'TS'
import { fare } from "./fares.mjs";
console.log(fare * 3);
TS

  tsc --strict --module nodenext --target es2020 --noEmitOnError --outDir out receipt.mts
  node out/receipt.mjs
)

Expected output#

Text
12

Common mistakes#

When emitting JavaScript for Node.js ESM, write the emitted extension in relative imports. TypeScript resolves ./fares.mjs to fares.mts and preserves the specifier for Node.js. The paths setting also leaves emitted import specifiers intact. Configure the corresponding alias in the runtime or bundler.

Version applicability#

TypeScript 4.7 introduced nodenext and the .mts to .mjs support used in the example. Its output uses ES2015 module syntax. TypeScript 5.0 introduced bundler resolution, which permits extensionless relative imports.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0