Sub topic 2
Install TypeScript and create tsconfig.json
This chapter sets up the compiler for a JavaScript project. By the end you will have TypeScript installed as a dev dependency, a working tsconfig.json, and a clear idea of what each option does and why it is set the way it is.
Prerequisites
This chapter assumes you have:
- Node.js and npm installed, and a terminal you are comfortable using.
- An existing JavaScript project with a
package.jsonfile and asrcfolder. - Working knowledge of modern JavaScript, in either CommonJS (
require) or ES modules (import). - A basic idea of what static types are.
Why install TypeScript per project
You can install TypeScript globally, but a project-local install is the better choice for a migration. Each project records its own compiler version in package.json. Teammates and CI then run the same compiler as you. A new compiler release can also change which errors you see, so pinning the version keeps the error list stable while you migrate.
Install the compiler and the Node.js type declarations as dev dependencies:
npm install --save-dev typescript @types/node
npx tsc --initThe three pieces do different jobs:
| Piece | What it does |
|---|---|
| `typescript` | Provides the `tsc` compiler, which checks types and emits JavaScript. |
| `@types/node` | Describes Node.js built-ins such as `fs`, `path`, `process` and `Buffer`, so the compiler knows their types. |
| `npx tsc --init` | Creates a starter `tsconfig.json` in the current folder. |
npx runs the tsc binary from your local node_modules/.bin. That is why you do not need a global install.
You can confirm the install worked by printing the version:
npx tsc --versionWhat tsconfig.json does
tsconfig.json tells the compiler which files belong to the project and how strictly to check them. When you run tsc with no file arguments, it looks for this file in the current folder and then in parent folders. If you pass file names on the command line, tsc ignores tsconfig.json. That is a common surprise, so prefer plain npx tsc once the file exists.
The file generated by --init contains many commented-out options. That is useful for reference but noisy. For a migration it is clearer to start from a small file that you fully understand.
A starting configuration
Replace the generated contents with this:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false
},
"include": ["src"]
}This configuration compiles both .js and .ts files from src into dist. Strict checking is off so that you can turn it on in stages later in the tutorial.
Reading each option
targetsets the JavaScript version of the emitted code.ES2020keeps modern syntax such as optional chaining (?.) and nullish coalescing (??) as written, which Node.js 14 and later runs natively. Choose a lower target only if you must support older runtimes. The compiler then rewrites newer syntax into older equivalents.modulesets the module format of the emitted code.commonjsproducesrequireandmodule.exports. Use it when your project is CommonJS or when you are not sure. Projects that run as native ES modules need different settings, which the chapter on imports and exports covers.rootDiris the folder that holds your source files. The compiler mirrors its structure insideoutDir, sosrc/utils/format.tsbecomesdist/utils/format.js.outDiris where compiled JavaScript goes. Keeping output indiststops generated files from mixing with your source.allowJslets the compiler read and emit.jsfiles alongside.tsfiles. This is what makes file-by-file migration possible. The next chapter explores it in detail.esModuleInteropmakes default imports of CommonJS packages behave the way most developers expect, for exampleimport express from "express".skipLibCheckskips type checking of.d.tsdeclaration files, including those innode_modules. It speeds up builds and avoids errors in packages you do not control. Your own.tsfiles are still fully checked.strictis the master switch for the family of strict checks. Setting it tofalseis a deliberate choice for the early stage of a migration.includelists the folders or glob patterns that make up the project. Here, everything undersrc.
How the compiler finds files
The include setting is easy to get wrong, so it is worth knowing the rules:
- Paths in
includeare relative to the folder that containstsconfig.json. - A plain folder name such as
"src"means all supported files under it. The supported extensions include.ts,.tsxand.d.ts. WithallowJson,.jsand.jsxare included too. - By default,
excludecoversnode_modulesand theoutDir. If you setexcludeyourself, you replace those defaults, so list them again. - A file that is imported from an included file is pulled into the program even if
includedoes not list it.
You can check what the compiler actually picked up without producing any output:
npx tsc --listFilesOnlyIf your files are missing from the list, check include first. If extra files appear, check exclude and look for stray imports.
Check that the setup works
Create a small file to test the configuration. Save this as src/hello.ts:
interface Greeting {
name: string;
}
function greet(g: Greeting): string {
return "Hello, " + g.name;
}
console.log(greet({ name: "world" }));Compile and run it:
npx tsc
node dist/hello.jsYou should see Hello, world. The compiler wrote dist/hello.js, and Node.js ran the plain JavaScript output. Delete src/hello.ts and dist/hello.js afterwards, since they were only a test.
The type-check-only workflow
During a migration you often want errors without writing any files. Add the --noEmit flag:
npx tsc --noEmitThis runs the full type check and exits with a non-zero code if there are errors, but it writes nothing to dist. You can also record the command as an npm script so everyone uses the same one:
{
"scripts": {
"typecheck": "tsc --noEmit",
"build": "tsc"
}
}Then npm run typecheck checks types, and npm run build produces the output.
Common setup problems
| Symptom | Likely cause | Fix |
|---|---|---|
| `tsc: command not found` | TypeScript is not installed locally, or you ran `tsc` without `npx`. | Run `npx tsc`, or use an npm script. |
| `error TS18003: No inputs were found in config file` | `include` points at a folder that has no supported files. | Check the folder name and that `src` contains `.ts` or `.js` files. |
| `Cannot find name 'process'` or `Cannot find module 'fs'` | `@types/node` is missing. | Run `npm install --save-dev @types/node`. |
| `Cannot write file ... because it would overwrite input file` | With `allowJs`, a `.js` file is both an input and an output location. | Set `outDir` so that it is not inside `include`, for example `dist` next to `src`. |
| Output lands next to your source files | `outDir` is not set. | Add `"outDir": "dist"`. |
| Expected files are not compiled | `include` or `exclude` is filtering them out. | Run `npx tsc --listFilesOnly` and adjust. |
Where this fits in the migration
The diagram shows the order of work this chapter starts. Installing and configuring come first. Everything else in the tutorial builds on a project that compiles cleanly before you change any code.
A clean first run matters. If npx tsc --noEmit reports errors on untouched JavaScript, they usually come from configuration, such as a wrong include or a missing @types package, not from your code. With checkJs off, which is the default, the compiler does not type check .js files, so a clean run is the normal result at this stage.
Exercises
Exercise
You run npx tsc src/index.ts and the compiler ignores your allowJs and outDir settings. Why, and what should you run instead?
Show answer
When you pass file names on the command line, tsc does not read tsconfig.json. Run npx tsc with no file arguments so it uses the configuration file.
Exercise
Your project has src/app.js and src/utils/format.js, with rootDir set to src and outDir set to dist. Where does the compiler write the output for each file, and which option must be on for it to process them?
Show answer
It writes dist/app.js and dist/utils/format.js, because the folder structure under rootDir is mirrored in outDir. The allowJs option must be true so the compiler reads and emits .js files.
Exercise
Why does this chapter set "strict": false even though strict is recommended for finished projects?
Show answer
A migration turns an untyped codebase into a typed one gradually. With strict on from the start, the first compile can report hundreds of errors at once. Turning it off lets you convert files and fix the basic errors first, then enable the strict checks in stages.