Modules

Topic 1 of 3 in Modules and declarations8 min readIntermediateFree course

Overview

Real projects are split across many files. TypeScript uses standard JavaScript ES modules — import and export — and adds a few things on top: importing types, checking that every import exists, and resolving imports the same way your runtime or bundler will. This lesson covers the module features you’ll use every day and the settings that make them work.

Exports and imports

Any file with a top-level import or export is a module: its variables are private unless exported.

TypeScript
// src/math.ts
export const PI = 3.14159;

export function circleArea(r: number): number {
  return PI * r ** 2;
}

export type Point = { x: number; y: number };
TypeScript
// src/main.ts
import { circleArea, PI } from "./math.ts";
import type { Point } from "./math.ts";

const origin: Point = { x: 0, y: 0 };
console.log(circleArea(2), PI);

TypeScript checks every import: misspell circleArea and you get an error immediately, with a suggestion. Renaming an export with F2 updates every import across the project.

Default exports

TypeScript
// logger.ts
export default function log(message: string) { … }

// main.ts
import log from "./logger.ts";
import anyName from "./logger.ts";   // also works — the importer picks the name

Because importers choose the name, default exports are harder to search for and refactor. Many teams use named exports only. You’ll still meet default exports in libraries and frameworks (React components, config files).

Other import forms

TypeScript
import * as math from "./math.ts";        // namespace import: math.PI, math.circleArea
export { circleArea as area } from "./math.ts";   // re-export under another name
export * from "./math.ts";                // re-export everything (index files)
const { circleArea } = await import("./math.ts");  // dynamic import, fully typed

Importing types

Types don’t exist at run time, so importing one should leave no trace in the JavaScript:

Modules: what is kept and what is erased. user.ts has export type User = { name: string }; and export function createUser(name: string) { return { name } satisfies User; }; the JavaScript output keeps only the function, without types. app.ts has import { createUser, type User } from “./user.ts”; the output is import { createUser } from “./user.js”. Type-only exports and imports disappear from the output. Mark them with type so every tool can drop them safely — verbatimModuleSyntax makes this a rule: anything without type is kept exactly as written.

Two equivalent spellings:

TypeScript
import type { User, Order } from "./models.ts";       // the whole import is types
import { createUser, type User } from "./models.ts";  // mixed: type marks one name

Why bother? Tools that strip types file by file — Node, esbuild, Vite, Vitest — can’t look into models.ts to find out whether User is a type. If an import of a type survived into the JavaScript, Node would fail with “does not provide an export named ‘User’”. Marking type imports makes them safe to delete.

The verbatimModuleSyntax option turns this into a rule: imports without type are kept exactly as written, and TypeScript reports type imports that aren’t marked:

Text
error TS1484: 'User' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.

Your editor can fix these automatically, and it adds type for you when it auto-imports.

File extensions

How you write the path in an import depends on who resolves it.

Code that Node runs (module: nodenext)

Node’s ES module loader requires the full file name. When Node runs your .ts files directly (as in this course), that means writing .ts:

TypeScript
import { add } from "./money.ts";

This needs allowImportingTsExtensions (which requires noEmit) in tsconfig. If instead you compile with tsc to JavaScript and run the output, you either write .js in your imports (TypeScript maps ./money.js to money.ts while checking), or write .ts and enable rewriteRelativeImportExtensions so tsc rewrites them to .js in its output.

Forget the extension under nodenext, and TypeScript tells you before Node does:

Text
error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './money.js'?

(The suggestion assumes you compile to JavaScript; when Node runs your .ts files directly, write ./money.ts.)

Code a bundler builds (moduleResolution: bundler)

Vite, webpack and similar tools resolve imports themselves and allow extension-less paths (import { add } from "./money"). For those projects, use:

JSON
{ "compilerOptions": { "module": "esnext", "moduleResolution": "bundler" } }

Project templates (such as npm create vite) set this up for you.

ES modules vs CommonJS

Older Node code uses CommonJS (require / module.exports). Modern TypeScript projects should be ES modules: set "type": "module" in package.json and module: "nodenext" in tsconfig, and TypeScript follows Node’s rules for each file — including the interop rules when an ES module imports a CommonJS package. You can still import most CommonJS packages from ES modules; TypeScript checks that you do it in a way Node supports.

Importing JSON

TypeScript
import settings from "./settings.json" with { type: "json" };

settings.theme;   // typed from the JSON file's contents

This needs resolveJsonModule in tsconfig (on by default with module: nodenext). TypeScript infers a type from the file — handy for configuration, though values are widened ("dark" becomes string).

Path aliases

Large apps often want import { db } from "#lib/db.ts" instead of ../../../lib/db.ts. The standard way is Node’s subpath imports, declared in package.json and understood by TypeScript (and, since TypeScript 6.0, with the #/ prefix too):

JSON
{ "imports": { "#lib/*": "./src/lib/*" } }

TypeScript’s own paths option still exists, but it only affects type checking — your runtime or bundler must be configured to match. (The old baseUrl option was removed in TypeScript 7.)

Remember: export what others need (by name), mark type imports with type, write the extensions Node expects, and let verbatimModuleSyntax keep your imports honest.

Exercise

A money module

Split a program into two files. src/money.ts exports: a type Currency ("USD" | "EUR" | "INR"), a type Money ({ amount: number; currency: Currency }), a const SYMBOLS (a Record<Currency, string>), and functions money(amount, currency): Money, add(a: Money, b: Money): Money (throw if currencies differ) and format(m: Money): string (₹1,250.50, using toLocaleString("en-IN", …) for 2 decimals). src/main.ts imports the functions with a normal import and the types with import type (or inline type), adds two INR amounts, and prints the formatted total and the list of supported currencies. Make sure it runs with node src/main.ts and passes tsc with verbatimModuleSyntax.

TypeScript
// ---- src/money.ts ----
export type Currency = "USD" | "EUR" | "INR";

// ---- src/main.ts ----
// import from "./money.ts"

Summary

  • Every file with an import or export is a module with its own scope; export what other files need.
  • Prefer named exports; they autocomplete, rename safely and can’t be imported under the wrong name.
  • Import types with import type or import { type X }; with verbatimModuleSyntax, that’s required.
  • Under module: nodenext, relative imports need file extensions — .ts when Node runs your source directly.
  • Use moduleResolution: bundler for apps built by Vite and similar tools, nodenext for code Node runs.