Sub topic 9
Rebuilding on change with watch mode
This chapter assumes you can run npx tsc in a project with a tsconfig.json, as set up in the previous chapters. You should also know what include, outDir, and noEmit do. It covers what tsc --watch does, how to configure it, and the problems you are most likely to hit.
What watch mode does
Running npx tsc compiles the project once and exits. Watch mode keeps the compiler running instead. It type-checks the whole project, emits JavaScript, and then waits. When you save a file, it recompiles and prints the new error count.
npx tsc --watchThe short form is -w. The command reads tsconfig.json from the current directory, so all your options apply exactly as in a normal build.
A typical session looks like this:
[10:15:02] Starting compilation in watch mode...
[10:15:04] Found 0 errors. Watching for file changes.After you save a file with a mistake in it, the compiler prints the diagnostics and a new summary:
[10:16:41] File change detected. Starting incremental compilation...
src/index.ts:4:19 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
[10:16:41] Found 1 error. Watching for file changes.The process does not exit when it finds errors. Stop it with Ctrl+C. Because it never exits on its own, its exit code is not useful in scripts. Use a plain tsc or tsc --noEmit in CI.
Why it is faster than rerunning tsc
Each tsc run has to start Node, parse tsconfig.json, find and parse every source file, and parse the type declarations from node_modules. Most of that is repeated work when you change one line.
Watch mode keeps the program in memory. When a file changes, the compiler reparses that file and re-checks it, along with any files that depend on it. Files whose inputs did not change are reused. This is why the second compile in a session is usually much quicker than the first.
Since the format needs the diagram fence as specified, here is the loop:
A worked example
Create a small project to see the loop. Assume the tsconfig.json from the earlier chapter (rootDir is src, outDir is dist).
// src/greet.ts
export function greet(name: string): string {
return `Hello, ${name}!`;
}// src/index.ts
import { greet } from "./greet";
console.log(greet("Ada"));Start the compiler in one terminal:
npx tsc --watchIt writes dist/index.js and dist/greet.js. In a second terminal, run the output with Node's own file watcher, which restarts the program when dist changes:
node --watch dist/index.jsnode --watch is available from Node 18.11. Now edit greet.ts and change the template string to Hi, ${name}!. Save the file. The first terminal recompiles greet.js, and the second restarts the program and prints Hi, Ada!. Two processes cooperate here. tsc turns TypeScript into JavaScript, and Node reruns the JavaScript.
Now introduce an error by changing the call in index.ts to greet(42). The compiler reports error TS2345. By default, it still writes the JavaScript, so Node would run the code and print Hi, 42!. That is usually not what you want while developing, which brings up the next point.
Interaction with emit options
Watch mode respects the emit options from the previous chapter. Three combinations come up often.
| Setting | Behavior in watch mode |
|---|---|
| Default | Emits JavaScript on every change, even when there are type errors. |
| `noEmitOnError: true` | Skips writing files for any compilation with errors. The old `dist` output stays until you fix the error. |
| `noEmit: true` | Type-checks on every change and writes nothing. Useful when a bundler or runner produces the output. |
With noEmitOnError, a stale dist can confuse you, because the running program is still the last good build. Look at the compiler terminal for the error count before you debug the running program.
The noEmit combination is the one to use when another tool transpiles your code. Run npx tsc --noEmit --watch beside your dev server. The editor and the server get fast feedback, and tsc acts as a dedicated type checker.
Configuring the watcher
The tsconfig.json file accepts a top-level watchOptions object. It sits beside compilerOptions, not inside it.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"rootDir": "src",
"outDir": "dist",
"sourceMap": true,
"skipLibCheck": true
},
"include": ["src"],
"watchOptions": {
"watchFile": "useFsEvents",
"watchDirectory": "useFsEvents",
"fallbackPolling": "dynamicPriorityPolling",
"excludeDirectories": ["**/node_modules", "dist"]
}
}The options mean the following:
watchFilesets how individual files are watched. The defaultuseFsEventsasks the operating system for change notifications. The polling values (fixedPollingInterval,priorityPollingInterval,dynamicPriorityPolling) check file timestamps on a timer instead.watchDirectorysets how directory trees are watched. It is used to notice new and deleted files. Its values includeuseFsEvents,fixedPollingInterval, anddynamicPriorityPolling.fallbackPollingapplies when the system cannot deliver file events. It selects the polling strategy to use instead.excludeDirectoriesandexcludeFilesstop the watcher from observing paths. Excludingnode_modulesand your output directory reduces load.
These options affect only how changes are detected. They never change which files are part of the program. That is still decided by include, exclude, and files.
You can also set these on the command line, for example --watchFile fixedPollingInterval. Command-line flags override the config file.
Reading the output
By default, tsc clears the terminal before each recompile in watch mode. That keeps the screen showing only the current errors. If you want to keep earlier output, for example when running alongside other tools, add --preserveWatchOutput:
npx tsc --watch --preserveWatchOutputThis flag is also needed when several processes share one terminal, because the clearing would erase their messages. The --pretty flag controls colors and code excerpts in diagnostics. Terminals usually enable it by default, but output that is piped may need --pretty true.
Using watch mode in package scripts
Put the commands in package.json so the team uses the same ones:
{
"scripts": {
"build": "tsc",
"typecheck": "tsc --noEmit",
"dev:tsc": "tsc --watch --preserveWatchOutput",
"dev:run": "node --watch dist/index.js"
}
}Run npm run dev:tsc and npm run dev:run in separate terminals. To run both from one command, install a process runner such as concurrently as a dev dependency and call both scripts from a dev script. Either way, tsc --watch stays a separate process from the code it builds.
Common problems
A new file is not compiled. The file is probably outside include. Watch mode picks up new files only when they match include (or files). A file in the project root, when include is ["src"], is ignored without any message.
Changes to tsconfig.json are not picked up the way you expect. The compiler watches the config file itself and reloads it. If it appears stuck after a big change, such as changing module, stop and restart it. This also clears any odd state.
Nothing happens after a save, especially in Docker, a VM, or a network drive. File-system events often do not cross those boundaries. Switch to polling:
{
"watchOptions": {
"watchFile": "fixedPollingInterval",
"watchDirectory": "fixedPollingInterval"
}
}Polling uses more CPU, so use it only where events fail.
On Linux, you see errors about the watcher limit (ENOSPC). The system limit on inotify watches is too low for the number of files being watched. Raise the limit in the operating system, or exclude large directories with excludeDirectories.
Errors remain after you fixed the code. Check that you saved the right file, and that the editor did not write to a different location. If the message refers to a type in node_modules, a package update may have changed declarations. Restarting the process forces a full rebuild.
Editor shows different errors than the terminal. The editor uses its own TypeScript server. If it uses a different compiler version than the one in your project, the results can differ. Select the workspace version of TypeScript in your editor so both use the version in node_modules.
Summary of when to use which command
| Goal | Command |
|---|---|
| Build once for deployment | `npx tsc` |
| Rebuild JavaScript while developing | `npx tsc --watch` |
| Type-check only, once (CI) | `npx tsc --noEmit` |
| Type-check only, continuously, beside a bundler or runner | `npx tsc --noEmit --watch` |
Exercise
You run npx tsc --watch with noEmitOnError set to true. You introduce a type error and save, but the program that runs dist/index.js still shows the old behavior. Why, and where should you look first?
Show answer
With noEmitOnError, tsc does not write any output for a compilation that has errors, so dist keeps the last successful build and the running program uses it. Look at the terminal running tsc --watch first. It shows the error and a count above zero.
Exercise
Your project's source is in src, and include is ["src"]. You add scripts/seed.ts while tsc --watch is running. Nothing is compiled and no error is shown. What is the cause, and what is the fix?
Show answer
scripts/seed.ts is not matched by include, so it is not part of the program and the watcher ignores it. Add "scripts" to include (and adjust rootDir, since both folders must sit under it), or give the scripts their own tsconfig. Then restart the watcher.
Exercise
A teammate runs tsc --watch inside a Docker container with the source folder mounted from the host. Saving files on the host never triggers a recompile. Which watchOptions change would you try?
Show answer
Set watchFile and watchDirectory to a polling strategy such as fixedPollingInterval, because file-system events often do not reach the container. Accept the extra CPU cost, and exclude node_modules with excludeDirectories to limit it.