Course contentsShow
← TypeScript
Lesson 1116 of 1,79626. Modules in TypeScriptFree lesson

The exports Field for Modern Packages

Understanding package.json exports and how TypeScript resolves subpath patterns.

The exports Field for Modern Packages

You'll learn how TypeScript uses the exports field in package.json to resolve module paths in modern npm packages.

What Is the exports Field?

The exports field in package.json is a modern, more powerful replacement for the older main and types fields. It gives package authors fine-grained control over which files can be imported and how subpaths are resolved.

Think of it like a building directory map: instead of letting people wander anywhere, you explicitly list which rooms (files) are accessible and what paths lead to them. Without exports, any file in a package could theoretically be imported; with exports, only the paths you define are accessible.

How TypeScript Resolves with exports

When TypeScript encounters an import from a package with an exports field, it follows these resolution rules:

  1. Checks for exports first — if present, uses only those paths
  2. Looks for type-specific entries — keys like types or import with TypeScript conditions
  3. Follows subpath patterns — matches wildcards like "./utils/*"
  4. Falls back gracefully — if no match, resolution fails (no default file crawling)

The exports field works alongside moduleResolution: "node16" or "bundler" settings in your tsconfig.json — older resolution strategies may ignore it.

Basic exports Example

{
  "name": "my-library",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    },
    "./utils": {
      "types": "./dist/utils.d.ts",
      "import": "./dist/utils.mjs"
    }
  }
}

Here, users can import from "my-library" or "my-library/utils" but nothing else. TypeScript finds the .d.ts file via the types condition.

Subpath Patterns

The exports field supports wildcards for flexible subpath mapping:

{
  "exports": {
    "./features/*": {
      "types": "./dist/features/*.d.ts",
      "import": "./dist/features/*.js"
    }
  }
}

Now import { x } from "my-library/features/auth" resolves to dist/features/auth.d.ts for types and dist/features/auth.js at runtime.

Why This Matters for TypeScript Users

  • Encapsulation: Package internals stay private; only documented paths work
  • Multi-format support: Different files for ESM vs CommonJS without confusion
  • Type safety: The types condition ensures TypeScript always finds the right .d.ts files
  • Modern resolution: Works seamlessly with bundlers and Node.js 12+ module systems

Key Takeaway: The exports field gives packages explicit control over importable paths and lets TypeScript reliably locate type definitions through conditional types entries and subpath patterns.