Thuta Learning
TypeScript
IntermediateProgrammingIntermediate

ESM Modules & Package Boundaries

TypeScriptLesson 1430 min

What you'll walk away with

  • Export functions, types and values from one file and import them in another with named imports
  • Explain why a relative import in a NodeNext project ends in .js even though the source file is .ts
  • Use import type so that type-only imports are erased from the emitted JavaScript
  • Describe how package.json "type" and "exports" define a package's module format and public surface

Explain it simply

Modules, in plain language

A module is simply a file that keeps its own variables private and chooses what to share. Anything you mark with export becomes available to other files; everything else stays hidden inside. Another file pulls in what it needs with import.

Think of each file as a small shop with a front counter: export puts an item on the counter, and import is a customer asking for that item by name. This lets a large program be split into small files that each do one job, without every name leaking into one big shared space.

Problem → Why → Solution

The problem: an import that looks fine but crashes in Node

Picture a project where every helper lives in one 3,000-line utils.ts, or worse, where scripts talk to each other through global variables. If two files each define a function called format, whichever loads last wins.

Then you split the code into files and hit the next surprise: Node.js crashes with ERR_MODULE_NOT_FOUND because an import path has no file extension.

src/app.ts
// package.json has "type": "module"
import { add } from "./math"; // no extension

console.log(add(2, 3));

// With "module": "NodeNext", tsc reports error TS2835 here.
// With older settings it compiles, then at runtime:
//   node dist/app.js
//   Error [ERR_MODULE_NOT_FOUND]: Cannot find module '.../dist/math'

Why this happens

Node's ES module loader does not guess file extensions the way the older CommonJS require() did; it loads exactly the path you write. TypeScript does not rewrite import paths when it emits JavaScript, so the path in your .ts source must be the path that is correct for the emitted .js file.

Core concept: export, import and the runtime path

ES modules (ESM) are the standard JavaScript module system, and TypeScript uses the same syntax. A file becomes a module as soon as it contains a top-level import or export. Inside a module, top-level names are private by default; export makes a name visible and import brings it in. You can export functions, classes and constants, and also types and interfaces.

There are two styles of export. A named export (export function add) is imported with braces and its exact name: import { add } from "./math.js". A default export (export default function) is imported without braces, under any name you like. Named exports are easier to search for and to rename safely, so many teams prefer them.

text
Source files, compiled files and the import path
------------------------------------------------
src/math.ts                        src/app.ts
-----------                        ----------
export function add(...)  <------  import { add } from "./math.js";
const SECRET = 42;  (not exported: app.ts cannot see it)

        | tsc compiles each file, import strings stay as written
        v

dist/math.js  <------------------  dist/app.js loads "./math.js"

That diagram explains the .js extension. TypeScript compiles math.ts to math.js but leaves the import string untouched, and at runtime app.js must point to a file that really exists, which is math.js. So with module and moduleResolution set to NodeNext you write the output file's extension, and TypeScript understands that ./math.js means ./math.ts while type-checking. Projects built by a bundler such as Vite can use moduleResolution: "bundler", which allows extensionless imports because the bundler resolves them.

Types vanish at runtime, so an import that only brings in types has nothing to load. Writing import type { User } from "./user.js" says so explicitly, and the whole line is erased from the output. With the verbatimModuleSyntax option, TypeScript requires this marker, so every remaining import is a real runtime import. Finally, Node decides whether a .js file is ESM or CommonJS from the nearest package.json: "type": "module" means ESM.

A mental model to remember
  1. Every file is its own private scope
  2. export puts a name on the counter
  3. import points at the emitted .js path
  4. import type disappears at runtime

TypeScript never rewrites your import path, so write the path that will be right at runtime.

General pattern

typescript
// lib.ts: share names with export
export function name(param: Type): Result { /* ... */ }
export type Shape = { field: Type };
export default function main() { /* ... */ }

// app.ts: bring them in with import
import main, { name } from "./lib.js"; // default + named
import type { Shape } from "./lib.js"; // type-only, erased

// index.ts: re-export (a "barrel" file)
export { name } from "./lib.js";

Named exports are imported with braces, the default export without them. In a NodeNext project write relative paths with .js, and mark type-only imports with import type.

A module that imports and exports

Two files such as math.ts and app.ts cannot share one code block and still run, because as a single file there is no ./math.js to import. So this example is one self-contained module: it imports from Node's built-in node:path module and exports its own API. In a real project, app.ts would use it with import { labelFor } from "./file-label.js".

file-label.ts
// file-label.ts: an ES module that imports from another module and exports its own API
import { basename, extname } from "node:path"; // named imports
import type { ParsedPath } from "node:path"; // type-only import: erased from the JS

export type FileLabel = { slug: string; ext: string }; // exported type

const MAX_SLUG = 20; // not exported: private to this module

export function labelFor(file: string): FileLabel {
  const ext = extname(file);
  const slug = basename(file, ext).toLowerCase().replace(/[^a-z0-9]+/g, "-");
  return { slug: slug.slice(0, MAX_SLUG), ext };
}

export function joinName(parts: Pick<ParsedPath, "name" | "ext">): string {
  return parts.name + parts.ext;
}

console.log(labelFor("src/My Report 2026.ts"));
console.log(joinName({ name: "math", ext: ".ts" }));

Code breakdown

  1. Line 2import { basename, extname } from "node:path";

    Two named imports from another module. The names must match exactly what node:path exports.

  2. Line 3import type { ParsedPath } from "node:path";

    A type-only import. ParsedPath is only used in a type annotation, so this whole line is erased from the compiled JavaScript.

  3. Line 5export type FileLabel = { slug: string; ext: string };

    Exports a type so other files can use it with import type { FileLabel }.

  4. Line 7const MAX_SLUG = 20;

    No export, so this constant is private to the module. Another file that tries to import it gets a compile error.

  5. Lines 9-13export function labelFor(file: string): FileLabel {

    The module's public API. It uses the imported helpers and the private constant, and returns { slug, ext }.

You should see
{ slug: 'my-report-2026', ext: '.ts' }
math.ts

Package boundaries: the exports field

When your code becomes a package that other projects install, the exports field in package.json becomes the package's front counter. Only the paths listed there can be imported, and deep imports into internal files fail. TypeScript follows this field when moduleResolution is NodeNext or bundler, and the types condition points it at the declaration files.

package.json
{
  "name": "@acme/money",
  "type": "module",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "default": "./dist/index.js"
    }
  }
}

Freedom to reorganise internals

Consumers can import from "@acme/money", but importing "@acme/money/dist/internal.js" is refused by Node with ERR_PACKAGE_PATH_NOT_EXPORTED. That lets you reorganise internal files without breaking anyone.

In real projects

How real projects organise modules

A Node.js backend usually gives each feature its own folder: users/ holds user.types.ts, user.service.ts and user.routes.ts. The service imports the types with import type, and the routes file only uses the service's named exports. Things like a database client are created once in one module and exported. Module code runs only once, on first import, and is then cached, so every importer shares the same instance.

When shared code is split into packages inside a monorepo, each package's exports field defines what other teams may depend on. An index.ts barrel file is handy for re-exporting the public API from one place, but huge barrels that re-export hundreds of files can slow down tests and bundlers, so keep them at package boundaries.

Common mistakes

Common mistakes

1. Leaving out the extension, or writing .ts

In a NodeNext project "./math" gives error TS2835, and with older settings it fails only at runtime with ERR_MODULE_NOT_FOUND. Writing "./math.ts" is only allowed with special options such as allowImportingTsExtensions, in setups where tsc itself does not emit the JavaScript. Write "./math.js", the path of the emitted file.

2. Mixing up default and named imports

If math.ts has the named export export function add, then import add from "./math.js" fails with "has no default export"; you need import { add } with braces. The reverse, importing an export default with braces, fails too. The import form must match the export form.

3. Two files importing each other

When a.ts imports b.ts and b.ts imports a.ts, you have a circular import. If one module's top-level code uses the other's const or class while it is still being evaluated, you get a ReferenceError: "Cannot access before initialization". Move the code both need into a third module.

Best practices

Best practices

  • Use NodeNext for module and moduleResolution in new Node projects, and "bundler" in bundler projects.
  • Turn on verbatimModuleSyntax so every type-only import is clearly marked with import type.
  • Prefer named exports over default exports; they are easier to find and safer to rename.
  • When you publish a package, limit its public paths with the exports field.

Mini challenge

A temperature.ts module

Write a module that exports a public API and keeps a helper private. Use a named import from a built-in module to self-check your function.

  • Export type Reading = { city: string; celsius: number }.
  • Export toFahrenheit(celsius) as a named export, rounded to one decimal place.
  • Keep a round1 helper private (not exported).
  • Make formatReading the default export, returning a string like "Yangon: 31.5 C / 88.7 F".
  • Import strictEqual from node:assert/strict and check that toFahrenheit(100) is 212.
temperature.ts
// TODO: named import of strictEqual from "node:assert/strict"

// TODO: export type Reading with city (string) and celsius (number)

function round1(value: number): number {
  // TODO: round to one decimal place (keep this helper private)
  return value;
}

// TODO: export function toFahrenheit(celsius: number): number

// TODO: export default function formatReading(r: Reading): string

// TODO: self-check toFahrenheit(100) with strictEqual, then print two readings

Expected: The self-check passes and two lines are printed: "Yangon: 31.5 C / 88.7 F" and "Mandalay: 38 C / 100.4 F".

Show hint

F = C * 9 / 5 + 32. Math.round(value * 10) / 10 rounds to one decimal place. A real app.ts would write import formatReading, { toFahrenheit, type Reading } from "./temperature.js".

Show solution
temperature.ts
import { strictEqual } from "node:assert/strict";

export type Reading = { city: string; celsius: number };

function round1(value: number): number {
  return Math.round(value * 10) / 10;
}

export function toFahrenheit(celsius: number): number {
  return round1((celsius * 9) / 5 + 32);
}

export default function formatReading(r: Reading): string {
  return `${r.city}: ${r.celsius} C / ${toFahrenheit(r.celsius)} F`;
}

strictEqual(toFahrenheit(100), 212); // throws if the formula is wrong
console.log(formatReading({ city: "Yangon", celsius: 31.5 }));
console.log(formatReading({ city: "Mandalay", celsius: 38 }));

Quick quiz 1 / 3

math.ts contains export function add. In a NodeNext project, which import in app.ts is correct?

Quick quiz 2 / 3

What remains in the emitted JavaScript for import type { User } from "./user.js";?

Quick quiz 3 / 3

A package.json has "exports": { ".": "./dist/index.js" }. What happens with import { x } from "pkg/dist/internal.js"?

What to remember

  • Names inside a module are private by default; only exported names can be imported.
  • In a NodeNext project, write relative imports with the emitted .js path; TypeScript does not rewrite paths.
  • import type removes type-only imports from the output.
  • package.json "type" sets the module format and "exports" defines the package's public surface.

Modules Reference — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.