Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 96 ยท Modules and Declarations

Modules

Learn how TypeScript uses ES modules - named and default exports, import type, verbatimModuleSyntax, file extensions, and nodenext vs bundler resolution.

Every real TypeScript project is split into many files, and each file is a module: it has its own scope, and it shares values and types with other files only through export and import. TypeScript uses the standard JavaScript module system (ES modules) that you may know from the JavaScript modules lesson. Almost everything you know from JavaScript carries over unchanged.

TypeScript adds two things on top. First, modules can export and import types as well as values, and because types are erased before the code runs, you sometimes need to tell the compiler which imports are type-only. Second, the compiler has to find the file behind each import path the same way your runtime or bundler will, and that's what the module and moduleResolution options in tsconfig.json control. This lesson covers both, plus the practical rules that keep imports working in Node.js, bundlers and Node's built-in type stripping.

Our editor holds one file, main.ts, compiled with --module nodenext as an ES module. Multi-file examples in this lesson are read-only, and the runnable ones import Node's built-in modules or write small module files to a temporary folder at runtime and load them with import().

Exporting and importing

A file becomes a module as soon as it contains a top-level import or export. Everything declared in it is private unless you export it. Here's a small two-file project:

TypeScript
// geometry.ts
export interface Point {
  x: number;
  y: number;
}

export const ORIGIN: Point = { x: 0, y: 0 };

export function distance(a: Point, b: Point): number {
  return Math.hypot(b.x - a.x, b.y - a.y);
}

function round(n: number): number {
  return Math.round(n * 100) / 100; // not exported: private to this file
}

export { round as roundTo2 }; // export under another name
TypeScript
// main.ts
import { distance, ORIGIN, type Point } from './geometry.js';
import * as geometry from './geometry.js';

const target: Point = { x: 3, y: 4 };
console.log(distance(ORIGIN, target)); // 5
console.log(geometry.roundTo2(Math.PI)); // 3.14

The import forms are the JavaScript ones:

Syntax Meaning
import { a, b } from './m.js' Named imports
import { a as alias } from './m.js' Named import under a different local name
import * as m from './m.js' Namespace import: an object holding every export
import thing from './m.js' Default import
import thing, { a } from './m.js' Default plus named
import './m.js' Run the module for its side effects only
const m = await import('./m.js') Dynamic import, returns a promise

Interfaces and type aliases are exported and imported exactly like values. The type keyword in type Point is optional here, but you'll see below why it's a good habit.

Node's built-in modules work the same way, so you can try every form in the editor:

TypeScript Named, namespace, default and dynamic imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

await import('node:os') is typed as the module's full export list, so os.EOL autocompletes and is checked. Top-level await works because the file is an ES module. If you need the type of a module without loading it, write typeof import('node:os').

Default exports vs named exports

A module can have one default export in addition to its named exports:

TypeScript
// logger.ts
export default class Logger {
  log(message: string): void {
    console.log(`[app] ${message}`);
  }
}

// main.ts
import Logger from './logger.js'; // any local name works
import Whatever from './logger.js'; // ...even this one

Many TypeScript teams prefer named exports for their own code:

  • The name is fixed by the exporting file, so every import site uses the same name, and "find all references" and automatic renames work reliably.
  • Editors can auto-import named exports from a list of names.
  • A file can grow from one export to several without changing how existing imports look.

Default exports are still common in framework conventions (a page component per file, for example) and in older packages. Use whatever the framework expects, and named exports elsewhere.

Re-exports and barrel files

A module can pass along exports from other modules:

TypeScript
// shapes/index.ts
export { distance, ORIGIN } from './geometry.js';
export type { Point } from './geometry.js';
export * from './polygons.js';
export * as colors from './colors.js';

A file like this, which only re-exports, is called a barrel. It gives a folder one tidy entry point (import { distance } from './shapes/index.js'). Use barrels sparingly in applications: importing one name from a big barrel can make tools load every module behind it, which slows down tests and builds.

Type-only imports and exports

Types are erased when TypeScript code runs (see How TypeScript Works). An interface Point exports nothing at runtime, so an import of Point must disappear from the output too. TypeScript has explicit syntax to mark an import or export as type-only:

TypeScript
import type { Point, Shape } from './geometry.js'; // whole statement is type-only
import { distance, type Point } from './geometry.js'; // only Point is type-only
export type { Point } from './geometry.js';
export { type Point, distance } from './geometry.js';

A type-only import can be used only in type positions. Using it as a value is an error:

TypeScript A type-only import used as a value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The run stops with main.ts(9,13): error TS1361: 'Stats' cannot be used as a value because it was imported using 'import type'. Stats is a class in Node, so it exists at runtime, but import type deliberately imports only its type. Using it as info: Stats on line 4 is fine. Remove the last line, and the program prints a folder for the current directory.

Why marking type imports matters

When tsc compiles your whole project, it knows which imported names are types, and it can drop those imports on its own. But many tools compile one file at a time without looking at other files: esbuild, SWC, Babel, Vite, and Node.js's built-in type stripping (node main.ts). Given import { area, Shape } from './shapes.ts', such a tool can't tell that Shape is an interface, so it keeps the import, and the JavaScript runtime then fails because shapes.ts exports no Shape at runtime.

You can watch that happen. The next example writes three small .ts files to a temporary folder and lets Node load them with its built-in type stripping, which removes type annotations without type checking:

TypeScript Type stripping needs type-only imports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

good.ts runs and prints the area, 9. bad.ts fails before any of its code runs: SyntaxError: The requested module './shapes.ts' does not provide an export named 'Shape'. Both files would pass a full tsc type check; only the explicit type keyword makes good.ts safe for one-file-at-a-time tools.

verbatimModuleSyntax

The verbatimModuleSyntax option turns this into a compile-time rule. Its idea is simple: what you write is what gets emitted. Imports without type are always kept; imports with type are always removed. And if you import a type without the type keyword, the compiler reports error TS1484 ("'Shape' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled").

JSON
{
  "compilerOptions": {
    "module": "nodenext",
    "verbatimModuleSyntax": true
  }
}

It's recommended for every new project, especially together with erasableSyntaxOnly when you run code with Node's type stripping (both are explained in the tsconfig lesson). Our editor doesn't enable it, but the examples in this course mark type-only imports anyway, so they'd compile with it on.

import { type A, b } and import type { A } behave slightly differently under verbatimModuleSyntax. If every name in import { type A } from './m.js' is type-only, the statement still remains in the output as import {} from './m.js', which runs the module for its side effects. import type { A } removes the whole statement. Prefer import type when you import only types.

File extensions in import paths

Under --module nodenext (what our editor and modern Node.js projects use), a relative import must include the file extension, exactly as Node.js requires at runtime. And here's the part that surprises everyone: in a .ts file you usually write .js, the name of the file that will exist after compilation:

TypeScript Missing extensions are errors under nodenext (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Both imports fail, for different reasons:

TEXT
main.ts(1,24): error TS2834: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Consider adding an extension to the import path.
main.ts(2,23): error TS2307: Cannot find module './utils.js' or its corresponding type declarations.

The first is the missing extension. The second has the right form, but our editor has no utils.ts next to main.ts. In a real project, TypeScript maps ./utils.js to ./utils.ts while type checking, and the compiled main.js then imports the compiled utils.js.

There are two other options for extensions:

  • Write .ts in the import (import { helper } from './utils.ts'). That's what Node's type stripping needs, because no .js file ever exists. Enable allowImportingTsExtensions (when tsc doesn't emit, with noEmit) or rewriteRelativeImportExtensions (TypeScript 5.7+, which rewrites .ts to .js in emitted code).
  • Use a bundler with moduleResolution: "bundler", which allows extensionless imports because bundlers like Vite and esbuild resolve them themselves.

Module resolution: nodenext vs bundler

Module resolution is how the compiler turns an import specifier ('./utils.js', 'zod', 'node:fs') into a file on disk. It must match what will happen at runtime, or you'll get code that type-checks and then fails to load. In TypeScript 7 there are two choices you'll actually use:

Setting Use it when Rules
"module": "nodenext" (implies moduleResolution: nodenext) Code runs directly in Node.js, including libraries you publish Relative imports need extensions; follows package.json "type" and "exports"; .mts files are always ESM and .cts files always CommonJS
"module": "esnext" or "preserve" with "moduleResolution": "bundler" Code is processed by a bundler (Vite, esbuild, webpack) or a runtime like Bun Extensionless relative imports allowed; still respects "exports" in packages

The old node10 resolution (sometimes written "moduleResolution": "node") was deprecated in TypeScript 6.0 and is gone in 7.0, along with baseUrl. If an old project relies on them, the migration lesson and What's New cover the upgrade.

ESM or CommonJS?

With nodenext, TypeScript decides per file whether it's an ES module or CommonJS, the same way Node.js does:

  • .mts files are ES modules; .cts files are CommonJS.
  • .ts files follow the nearest package.json: "type": "module" means ESM, otherwise CommonJS.

New projects should be ESM: put "type": "module" in package.json. You'll still meet CommonJS in older code and packages. TypeScript has a special syntax for importing CommonJS modules that use module.exports = ..., which you'll see in some declaration files:

TypeScript
import express = require('express'); // CommonJS-style import, only in CommonJS files
export = createApp; // CommonJS-style export

From an ES module, you can simply default-import a CommonJS package (import express from 'express'); Node hands you its module.exports object. That's why import fs from 'node:fs' worked in the first example.

Modules run once

A module's top-level code runs once, the first time anything imports it. Every later import gets the same, already-evaluated module, so a module is a natural singleton. Exported let variables are live bindings: importers see the current value, but only the exporting module can assign to them.

TypeScript One evaluation, shared state, live bindings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

evaluating counter.mjs is printed only once, both imports return the same module namespace object, and the second import sees count as 2. Marking count as readonly in CounterModule matches the runtime rule: assigning to an imported binding throws a TypeError.

Because the path is computed at runtime, TypeScript types this import(url) as Promise<any>. The as CounterModule assertion replaces that any with an honest description. With a literal path to a real file, like import('./counter.js'), you'd get the exact types for free.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does import type { User } from './models.js' produce in the compiled JavaScript?

    Type-only imports are always erased. Only the type checker uses them.
  2. 2. Why can import { area, Shape } from './shapes.ts' fail under Node's type stripping when Shape is an interface?

    Without the type keyword, a one-file-at-a-time tool can't know Shape is a type, so the runtime looks for an export that doesn't exist and throws a SyntaxError.
  3. 3. Under --module nodenext, how do you usually import utils.ts from main.ts in the same folder?

    nodenext requires extensions, and you write the extension of the emitted file, .js. TypeScript maps it back to utils.ts while type checking.
  4. 4. A module has export let count = 0; and two other files import it. One calls a function that increments count. What does the other file see?

    A module is evaluated once and all importers share it; exported bindings are live, so updates are visible everywhere.
  5. 5. Which moduleResolution setting should an app built with Vite use?

    bundler matches how bundlers resolve imports, including extensionless relative paths. node10 is removed in TypeScript 7, and classic is a legacy mode for very old code.

Summary

  • Every file with a top-level import or export is a module with its own scope; TypeScript uses standard ES module syntax for values and types alike.
  • Prefer named exports for your own code; default exports are fine where frameworks expect them. Barrels re-export, but use them sparingly.
  • Mark type-only imports with import type or the inline type modifier. One-file-at-a-time tools (esbuild, Vite, Node type stripping) depend on it, and verbatimModuleSyntax enforces it (TS1484).
  • With nodenext, relative imports need an extension, usually .js (or .ts with rewriteRelativeImportExtensions); missing extensions give TS2834.
  • Choose nodenext for code Node runs directly and bundler for bundled apps; node10 resolution and baseUrl are gone in TypeScript 7.
  • Modules are evaluated once and shared; exported let bindings are live and read-only to importers.

Next: Declaration Files (.d.ts)