Sub topic 14
Compile and Run the Result
This chapter assumes you have a tsconfig.json with allowJs, rootDir: "src" and outDir: "dist" (set up in earlier chapters). It also assumes you have renamed at least one file to .ts and fixed its compiler errors. Here you will compile the project, run the output, and handle the problems that usually appear at this step.
What the compiler produces
The TypeScript compiler, tsc, does two jobs. It checks types, and it emits JavaScript. Node.js never runs your .ts files directly. It runs the .js files that tsc writes into outDir.
Types are erased during emit. The output contains no interface, no annotations and no unknown. Because of this, a type error does not by itself stop the build. By default tsc reports the errors and still writes the files.
A small project to compile
Use this layout. The file src/format.ts is the converted file. src/index.js is still JavaScript, which shows allowJs working.
mkdir -p srcCreate src/format.ts:
export interface User {
name: string;
age: number;
email?: string;
}
export function formatUser(user: User): string {
return user.name.toUpperCase() + " (" + user.age + ")";
}Create src/index.js:
const { formatUser } = require("./format");
console.log(formatUser({ name: "Ada", age: 36 }));The require("./format") call has no extension. Node resolves it to format.js in dist, which is the compiled output of format.ts.
Run the compiler
Run tsc with no arguments. It reads tsconfig.json from the current directory.
npx tsc
node dist/index.jsExpected output:
ADA (36)After the build, dist holds format.js and index.js. The rootDir setting keeps the folder structure the same as src. Without rootDir, tsc picks the common parent folder of the inputs, and the layout in dist can change when you add a file elsewhere.
Look at dist/format.js to see the erasure:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatUser = formatUser;
function formatUser(user) {
return user.name.toUpperCase() + " (" + user.age + ")";
}The interface is gone. Because the file uses export, TypeScript treats it as a module and compiles it to CommonJS, as module: "commonjs" requests.
Type check without emitting
During migration you often want the errors but not the files. Use --noEmit.
npx tsc --noEmitThis is the command to use in editors, pre-commit hooks and CI. It is also faster, because it skips writing files. The exit code is non-zero when there are errors, which makes it usable as a gate.
Stop emitting on errors
By default the build writes output even when type errors exist. That helps in the middle of a migration, because you can keep running the app while you fix errors. It is risky in production, because a broken build can ship.
Set noEmitOnError once the project is clean enough:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false,
"noEmitOnError": true
},
"include": ["src"]
}With this flag, any type error means no files are written, and dist keeps its previous contents. Stale files in dist can then be mistaken for fresh ones, so check the exit code of tsc rather than looking at dist.
| Command | Checks types | Writes files | Typical use |
|---|---|---|---|
| `npx tsc` | Yes | Yes, even with errors | Local builds during migration |
| `npx tsc --noEmit` | Yes | No | CI, editor, pre-commit |
| `npx tsc` with `noEmitOnError` | Yes | Only if no errors | Release builds |
| `npx tsc --watch` | Yes | Yes, on each change | Active development |
Add npm scripts
Put the commands in package.json so everyone on the team uses the same ones.
{
"scripts": {
"typecheck": "tsc --noEmit",
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsc --watch"
}
}Run npm run build && npm start to compile and launch. For a watch loop, run npm run dev in one terminal and restart node in another, or use a tool such as nodemon dist/index.js.
Run TypeScript directly during development
Compiling before every run is slow for small scripts. Two common tools run .ts files directly:
ts-nodecompiles in memory and then runs the result. It type checks by default, which is slower.tsxstrips types and runs the file without checking them. It is fast, but it will not catch type errors.
npx tsx src/format.tsTreat these as convenience tools. For production, build with tsc and run the emitted JavaScript. If you use tsx, also run npm run typecheck, because tsx alone never reports type errors.
Common problems
Cannot find module after compiling
Symptom: Error: Cannot find module './format' when you run node dist/index.js.
Cause: dist/format.js does not exist. The usual reasons are that you ran node on src/index.js instead of the dist copy, that rootDir or include is wrong, or that noEmitOnError blocked the build. Run npx tsc --listEmittedFiles to see what was written.
JavaScript files missing from dist
Symptom: only .ts files appear in dist.
Cause: allowJs is false or missing. With allowJs off, tsc ignores .js files, so a remaining JavaScript file is never copied. Turn it on, as in the starter config.
Output overwrites the input
Symptom: tsc reports "Cannot write file ... because it would overwrite input file."
Cause: outDir is missing, or dist falls inside include. Keep include to ["src"] and outDir as dist.
ES module versus CommonJS mismatch
Symptom: ERR_REQUIRE_ESM or exports is not defined in ES module scope.
Cause: the module setting in tsconfig.json does not match what Node expects. If package.json has "type": "module", Node treats .js files as ES modules, but module: "commonjs" emits exports. Either remove "type": "module" or switch the project to ES modules with matching settings, such as "module": "nodenext". Keep this decision consistent across all files.
Source locations in stack traces
Stack traces point at dist/format.js line numbers, not at your .ts lines. Turn on source maps so tooling can map them back:
{
"compilerOptions": {
"sourceMap": true
}
}Then run Node with --enable-source-maps:
node --enable-source-maps dist/index.jsAdd sourceMap to your existing compilerOptions. Do not replace the whole object.
A runtime check types cannot give you
Compilation proves that your code is consistent with its declared types. It does not check data that arrives at runtime. If formatUser receives JSON from an API with age as a string, the program still runs and prints "Ada (36)" or something unexpected. This is why the earlier parseConfig example validates unknown input. After a successful build, test with real inputs, not only with the compiler.
Checklist for a clean build
npx tsc --noEmitexits with code 0.npx tscwrites both converted and remaining JavaScript files intodist.node dist/index.jsproduces the same output as the original JavaScript did.- Stack traces map to
.tslines whensourceMapand--enable-source-mapsare on. distis ignored by version control.
Exercise
You run npx tsc and see two type errors, but dist/index.js still exists and node dist/index.js works. Why, and which single setting changes this behavior?
Show answer
By default tsc emits JavaScript even when type checking fails, because types are erased and do not affect the emitted code. Setting "noEmitOnError": true in compilerOptions stops it from writing files when there are errors. Check the exit code of tsc, since an older dist could still be present.
Exercise
Your CI job only needs to know whether the types are valid and should not create files. Which command do you use, and how does CI know the check failed?
Show answer
Use npx tsc --noEmit. It exits with a non-zero status when type errors exist, and CI treats a non-zero exit code as a failed step.
Exercise
After the build, node dist/index.js fails with "Cannot find module './legacy'", and legacy.js is in src. What is the most likely configuration cause?
Show answer
allowJs is off, so tsc did not copy legacy.js into dist. Set "allowJs": true and rebuild. Running npx tsc --listEmittedFiles confirms which files were written.