Sub topic 14
Compile and Run the Result
Assume you already know modern JavaScript, Node.js, npm, and the purpose of tsconfig.json. This chapter focuses on the final build step: turning the converted .ts file into JavaScript and running the emitted program.
Understand the compile-and-run pipeline
TypeScript is usually not executed directly by Node.js. The TypeScript compiler, tsc, reads your .ts files, checks their types, and writes JavaScript files to the directory configured by outDir.
For example:
src/
formatUser.ts
dist/
formatUser.jsThe source file is for development. The emitted file is what Node.js runs.
Compile with `tsc`
A basic tsconfig.json might use these settings:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src"]
}Run the compiler from the project directory:
npx tscIf compilation succeeds, tsc creates JavaScript files under dist. It may also create source maps if "sourceMap": true is enabled. A source map connects generated JavaScript back to the original TypeScript, which makes debugger locations and stack traces easier to understand.
Run the emitted program with Node.js:
node dist/formatUser.jsNode.js does not need TypeScript installed at runtime. It only needs the generated JavaScript and any runtime dependencies that the program imports.
Make build commands repeatable
Add scripts to package.json so every developer and CI system uses the same commands:
{
"scripts": {
"build": "tsc",
"start": "node dist/formatUser.js",
"typecheck": "tsc --noEmit"
}
}Use them like this:
npm run build
npm startThe typecheck script checks the project without writing files. This is useful in continuous integration, where you want to reject type errors without changing the workspace.
Handle failed builds
By default, the compiler can emit JavaScript even when it reports some errors. During migration, that behavior can hide problems. Set noEmitOnError to prevent output when checking fails:
{
"compilerOptions": {
"noEmitOnError": true
}
}A failed build should stop the release pipeline. Fix the reported error in the .ts source, run npm run build again, and then run the generated JavaScript.
Verify the result
Check both stages separately:
npm run typecheckconfirms that the source passes TypeScript checking.npm run buildconfirms that JavaScript can be emitted.npm startconfirms that the emitted program runs.- Your tests confirm that behavior remained correct during conversion.
Exercise
Why should the command be node dist/formatUser.js rather than node src/formatUser.ts?
Show answer
Node.js normally runs JavaScript, while tsc converts the TypeScript source in src into executable JavaScript in dist.