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.
What you’ll build
Section titled “What you’ll build”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)Prerequisites
Section titled “Prerequisites”Node.js 22.18 or later and npm. Create the project and install TypeScript; the samples were compiled with TypeScript 7.0.2:
mkdir orders-portal-basics && cd orders-portal-basicsnpm init -ynpm pkg set type=modulenpm install -D typescriptmkdir srcModules and imports
Section titled “Modules and imports”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/:
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 };}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));}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 noUncheckedIndexedAccessconsole.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.tsimportsmoney.tsandmoney.tsimportscart.ts, one module runs before the other has finished, and a value read at load time can beundefined. 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.
Compiling with tsc
Section titled “Compiling with tsc”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.mapThe 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.tsignorestsconfig.json. Since TypeScript 6.0, runningtscwith file names in a folder that has atsconfig.jsonis 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 plaintscto use the configuration.- A clean type-check is not runtime validation.
tscreporting no errors means your code is consistent with its declared types, not that external data matches them.
Configuring tsconfig
Section titled “Configuring tsconfig”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:
npm run buildnpm startOutput:
first line: SKU-RED-01total: 23.99 EURWith 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 aserror TS5108: Option 'target=ES5' has been removed. - Turning
strictoff to silence errors. Each disabled check hides a category of bug; fix the errors instead.
Complete working result
Section titled “Complete working result”The finished project is the three source files from Modules and imports, the tsconfig.json and the scripts above. The daily workflow:
npm run typecheck # fast check, no output files; use this in CInpm run build # writes dist/*.js and dist/*.js.mapnpm start # node dist/main.jsnpx tsc --watch # rebuild on every save while you workOn 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.
Troubleshooting
Section titled “Troubleshooting”| 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"]. |
Check your understanding
Section titled “Check your understanding”- Why do you import
./cart.jswhen the file on disk iscart.ts? - What happens to
import type { Money } from "./money.js"in the compiled output? - What is the difference between
tscandtsc --noEmit? - Which
tsconfig.jsonoption would you add to useprocess.envin 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.
Next steps
Section titled “Next steps”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.
Related pages
Section titled “Related pages”- TypeScript basics overview
- Tooling and project structure: strict options, module settings, project references and TypeScript 7.
- Declarations and modules:
.d.tsfiles,@typesand module augmentation.