Skip to content

TypeScript modules, tsc and tsconfig.json

The earlier tutorials compiled one file at a time. Real projects have many files, a build command and a configuration that every developer and the CI server share. This last basics tutorial splits the OrdersPortal cart into ES modules, explains what the TypeScript compiler (tsc) does to your code, and sets up a tsconfig.json for a Node.js project. It assumes the previous three tutorials, ending with Objects, interfaces and classes.

A small project with three source files in src/ (money formatting, the cart total and a main.ts entry point), a tsconfig.json, and npm scripts to build, type-check and run it:

orders-portal-basics/
package.json
tsconfig.json
src/
money.ts
cart.ts
main.ts
dist/ (created by the build)

Node.js 22.18 or later and npm. Create the project and install TypeScript; the samples were compiled with TypeScript 7.0.2:

Terminal window
mkdir orders-portal-basics && cd orders-portal-basics
npm init -y
npm pkg set type=module
npm install -D typescript
mkdir src

TypeScript uses standard JavaScript modules: each file is a module, export makes a declaration visible to other files, and import brings it in. A module can have named exports and one export default. The runtime behavior, including how modules load once and how live bindings work, is covered on the JavaScript modules page.

TypeScript adds two things. First, you can export and import types (interfaces and type aliases) alongside values. A type-only import, import type { Money } from "./money.js" or the inline form import { cartTotal, type OrderLine } from "./cart.js", is removed entirely from the compiled JavaScript. Second, under Node.js module rules ("module": "nodenext", used below), a relative import must include the file extension, and you write the extension of the compiled file, .js, because tsc does not rewrite import paths.

Save these files in src/:

src/money.ts
export type Currency = "EUR" | "USD";
export interface Money {
readonly amount: number;
readonly currency: Currency;
}
export function formatMoney({ amount, currency }: Money): string {
return `${amount.toFixed(2)} ${currency}`;
}
export default function money(amount: number, currency: Currency = "EUR"): Money {
return { amount: Math.round(amount * 100) / 100, currency };
}
src/cart.ts
import money, { type Money } from "./money.js";
export interface OrderLine {
readonly sku: string;
quantity: number;
unitPrice: number;
}
export function cartTotal(lines: readonly OrderLine[]): Money {
return money(lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0));
}
src/main.ts
import { cartTotal, type OrderLine } from "./cart.js";
import { formatMoney } from "./money.js";
const lines: OrderLine[] = [
{ sku: "SKU-RED-01", quantity: 2, unitPrice: 9.5 },
{ sku: "SKU-BLU-02", quantity: 1, unitPrice: 4.99 },
];
const first = lines[0]; // OrderLine | undefined, because of noUncheckedIndexedAccess
console.log(`first line: ${first?.sku ?? "none"}`);
console.log(`total: ${formatMoney(cartTotal(lines))}`);

Importing "./cart" without the extension fails with error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './cart.js'?

Pitfalls:

  • Circular imports. If cart.ts imports money.ts and money.ts imports cart.ts, one module runs before the other has finished, and a value read at load time can be undefined. Type-only imports are erased, so they never cause this; for values, move the shared code into a third module.
  • Prefer named exports. A default export can be imported under any name, which makes searching and refactoring harder; many teams use named exports only.

tsc does two separate jobs. It type-checks the program and reports errors, and it emits JavaScript by removing the types (and, if target is older than your syntax, rewriting newer JavaScript features). Interfaces, type aliases, annotations and import type statements disappear completely; the output is the code you wrote, minus the types.

By default tsc still writes the JavaScript when there are type errors, so a project can run while it is being fixed; set noEmitOnError to stop that. tsc --noEmit type-checks without writing files, which is the usual CI step, especially when another tool (a bundler, or Node.js running .ts files directly) produces the JavaScript. tsc --watch recompiles whenever a file changes.

Types are erased, so they give no protection at run time: data from JSON.parse, an API or a form is whatever it is, regardless of the type you assign to it. Check such data before trusting it; see Type narrowing.

After the build below, dist/cart.js contains:

import money, {} from "./money.js";
export function cartTotal(lines) {
return money(lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0));
}
//# sourceMappingURL=cart.js.map

The OrderLine interface and the Money type are gone, and so are the parameter and return annotations. The empty {} is what is left of { type Money } under verbatimModuleSyntax, which keeps import statements exactly as written apart from their type-only parts; import type { Money } on its own line would be removed entirely.

Pitfalls:

  • tsc file.ts ignores tsconfig.json. Since TypeScript 6.0, running tsc with file names in a folder that has a tsconfig.json is an error: error TS5112: tsconfig.json is present but will not be loaded if files are specified on commandline. Use '--ignoreConfig' to skip this error. Run plain tsc to use the configuration.
  • A clean type-check is not runtime validation. tsc reporting no errors means your code is consistent with its declared types, not that external data matches them.

tsconfig.json marks the root of a TypeScript project. tsc without arguments looks for it in the current folder, compiles the files that include matches, and applies compilerOptions. Editors read the same file, so everyone gets the same errors.

TypeScript 6.0 changed several defaults, and TypeScript 7.0 kept them: strict is true, module is esnext, target is the newest ECMAScript edition, and types is [] (no global @types packages unless listed). It is still good practice to state the important options explicitly. Create tsconfig.json:

{
"compilerOptions": {
"target": "es2024",
"module": "nodenext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"sourceMap": true,
"types": []
},
"include": ["src"]
}

What each option does:

Option Effect
target Which JavaScript edition to emit; Node.js 22 supports ES2024 syntax.
module nodenext follows Node.js’s module rules, including required .js extensions.
rootDir, outDir src/main.ts compiles to dist/main.js. Set rootDir explicitly; since TypeScript 6.0 it defaults to the folder of tsconfig.json.
strict The family of strict checks, such as strictNullChecks and noImplicitAny.
noUncheckedIndexedAccess lines[0] is OrderLine | undefined, so you must handle a missing element.
verbatimModuleSyntax Type imports must say type, so other tools can strip them safely.
sourceMap Writes .js.map files so stack traces and debuggers point at your .ts source.
types Global type packages to load; add "node" after npm install -D @types/node to use process or node:fs.

Add npm scripts to package.json:

{
"scripts": {
"build": "tsc",
"typecheck": "tsc --noEmit",
"start": "node dist/main.js"
}
}

Then build and run:

Terminal window
npm run build
npm start

Output:

first line: SKU-RED-01
total: 23.99 EUR

With verbatimModuleSyntax, writing import { cartTotal, OrderLine } from "./cart.js"; fails with error TS1484: 'OrderLine' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled. Run npx tsc --showConfig to see every option that applies, including the ones implied by others.

Pitfalls:

  • Old tutorials, old options. Options such as "moduleResolution": "node", "baseUrl" and "target": "es5" were deprecated in TypeScript 6.0 and removed in 7.0; with 7.0 they stop the build with errors such as error TS5108: Option 'target=ES5' has been removed.
  • Turning strict off to silence errors. Each disabled check hides a category of bug; fix the errors instead.

The finished project is the three source files from Modules and imports, the tsconfig.json and the scripts above. The daily workflow:

Terminal window
npm run typecheck # fast check, no output files; use this in CI
npm run build # writes dist/*.js and dist/*.js.map
npm start # node dist/main.js
npx tsc --watch # rebuild on every save while you work

On Node.js 22.18 and later you can also run TypeScript files directly with node file.ts: Node.js strips the types without checking them. That needs .ts extensions in relative imports, so it does not mix with this project’s .js imports without extra configuration; the tooling hub explains the options.

Error What it means Fix
TS2835: Relative import paths need explicit file extensions ... An import under nodenext has no extension. Write ./cart.js, the compiled file’s name.
TS2307: Cannot find module './x.js' or its corresponding type declarations. The path is wrong, or the file is outside include. Check the path relative to the importing file and the include pattern.
TS1484: 'X' is a type and must be imported using a type-only import ... A type is imported like a value under verbatimModuleSyntax. Add type: import { type X } or import type { X }.
TS5112: tsconfig.json is present but will not be loaded ... tsc was given file names in a project folder. Run tsc without file names.
TS2591: Cannot find name 'process'. Do you need to install type definitions for node? ... Node.js types are not loaded. npm install -D @types/node and set "types": ["node"].
  1. Why do you import ./cart.js when the file on disk is cart.ts?
  2. What happens to import type { Money } from "./money.js" in the compiled output?
  3. What is the difference between tsc and tsc --noEmit?
  4. Which tsconfig.json option would you add to use process.env in this project?

Answers: (1) tsc emits imports unchanged and Node.js loads the compiled .js file; TypeScript maps the .js specifier back to cart.ts for type checking. (2) It is removed completely. (3) Both type-check; only tsc writes JavaScript files. (4) "types": ["node"], after installing @types/node.

You have finished the basics. Continue with the TypeScript topic hubs, starting with Core type system, or go straight to Tooling and project structure to learn more about configuration.