Sub topic 1
Setting up the project
This chapter creates the empty project that the rest of the tutorial fills in. You will install the compiler, write a package.json and a minimal tsconfig.json, and compile and run a one-line program. When that works, you have a toolchain you can trust, and later problems will be in your code, not your setup.
The finished tool is wcl, a small command that counts the lines and words in a file.
Prerequisites
This chapter assumes you have the following:
- Basic JavaScript or TypeScript syntax: functions, type annotations, and
async/await. - Node.js and npm installed, with comfort running commands in a terminal. Node.js 20 or later is recommended, because later chapters use
node:utilparseArgsand the built-innode:testrunner. - A basic understanding of
package.json: whatname,version, andscriptsmean.
Check your versions before you start:
node --version
npm --versionIf node --version prints something older than v20, upgrade first. Several errors later in the tutorial come from running on an old Node.js version.
What the setup has to achieve
Node.js cannot run TypeScript directly in the setup used here. You write .ts files in src, the TypeScript compiler (tsc) turns them into .js files in dist, and Node.js runs those. The setup must do four things:
- Install the compiler and the type definitions for Node.js APIs.
- Tell Node.js to treat the project's
.jsfiles as ES modules (ESM). - Tell the compiler where the source is, where the output goes, and which module rules to follow.
- Provide scripts so building is one command.
Creating the package
Create a directory and initialize a package in it:
mkdir wcl
cd wcl
npm init -yThe -y flag accepts every default and writes a package.json for you. Now install the two development dependencies:
npm install --save-dev typescript @types/nodeEach package has a different job:
typescriptprovides thetsccompiler.@types/nodeprovides type declarations for built-in modules such asnode:fs/promisesand for globals such asprocess. Without it, the compiler does not know these exist.
Both go under devDependencies because they are only needed to build the tool. The compiled output in dist does not import TypeScript, and the type declarations vanish at compile time. A user who installs wcl does not need either package.
Writing package.json
Open the generated package.json and replace its contents with the following, keeping the devDependencies block that npm added (it holds the exact versions it installed):
{
"name": "wcl",
"version": "1.0.0",
"type": "module",
"bin": { "wcl": "dist/cli.js" },
"files": ["dist"],
"scripts": {
"build": "tsc",
"test": "tsc && node --test dist"
}
}The devDependencies entry sits alongside these fields. You do not need to type it yourself.
Here is what each field does:
| Field | Purpose |
|---|---|
| `name` | The package name. It also becomes the default command name for global installs. |
| `version` | The package version, following semantic versioning. |
| `type` | `"module"` makes Node.js treat every `.js` file in the package as ESM. |
| `bin` | Maps the command name `wcl` to the file that runs when a user types it. |
| `files` | The list of paths included when the package is published or packed. Here only `dist`. |
| `scripts` | Named commands run with `npm run <name>`. |
The bin and test entries refer to files you have not written yet. Chapters on packaging and testing explain them. They are in place now so you do not have to revisit the file.
Why `"type": "module"`
Node.js supports two module systems. CommonJS uses require() and module.exports. ESM uses import and export. A .js file is read as CommonJS unless the nearest package.json says "type": "module".
This tutorial uses ESM for three reasons:
- ESM is the standard in the language, and new Node.js libraries increasingly publish only ESM.
- Top-level
awaitworks in ESM. The entry point in a later chapter uses it to call an asyncmainfunction without wrapping it. node:imports and TypeScript'sNodeNextsetting both work smoothly with it.
The cost is a rule you will meet right away: in ESM, relative imports must include the file extension. This is covered under common errors below.
Why `files` matters
Without a files list, npm packs nearly everything in the directory except a few defaults. That includes src, config files, and test files. With "files": ["dist"], only compiled output is published. npm always adds package.json and the README to the package, so you do not list them.
Configuring the compiler
The compiler needs a tsconfig.json in the project root. The next chapter explains each option in detail. For now, create this file so the build can run:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"outDir": "dist",
"rootDir": "src",
"types": ["node"]
},
"include": ["src"]
}In short: src is the input, dist is the output, and NodeNext makes the compiler follow the same module rules Node.js follows at runtime. strict turns on the full set of type checks. Keep it on from the first line of code, because turning it on later means fixing many errors at once.
Project layout
Create the source directory and a first file:
mkdir srcWhen the tutorial is finished, the project looks like this:
wcl/
├── package.json
├── tsconfig.json
├── .gitignore
├── src/
│ ├── cli.ts
│ ├── count.ts
│ └── count.test.ts
└── dist/ (generated, not committed)Source and tests live in src, and dist is generated by tsc. Because dist can be rebuilt at any time, keep it out of version control. Create a .gitignore:
node_modules
distA first build
Create src/cli.ts with a single line:
console.log("wcl is set up");Build it and run the output:
npm run build
node dist/cli.jsThe build prints nothing when it succeeds. A silent tsc is the normal success result. The second command should print wcl is set up.
Look at what appeared in dist:
ls distYou should see cli.js. The compiler removed types and wrote plain JavaScript. As you add files, each .ts file under src gets a matching .js file under dist, with the same relative path.
Common errors at this stage
Most setup failures come from a few causes. The table maps each symptom to its fix.
| Symptom | Cause | Fix |
|---|---|---|
| `Cannot find name 'process'` or `Cannot find module 'node:fs/promises'` | `@types/node` is not installed, or `types` in `tsconfig.json` does not include it. | Run `npm install --save-dev @types/node` and keep `"types": ["node"]`. |
| `SyntaxError: Cannot use import statement outside a module` | `"type": "module"` is missing, so Node.js reads `dist/*.js` as CommonJS. | Add `"type": "module"` to `package.json`. |
| `Cannot find module` or `ERR_MODULE_NOT_FOUND` when importing `./count` | ESM requires the extension in relative imports. | Write `import { countText } from "./count.js"`, even though the source file is `count.ts`. |
| `tsc: command not found` | You ran `tsc` directly and it is not installed globally. | Use `npm run build` or `npx tsc`. npm scripts find locally installed tools. |
| `error TS6059: File ... is not under 'rootDir'` | A `.ts` file outside `src` was included in the build. | Keep sources under `src` and keep `"include": ["src"]`. |
| Old behavior after you edit code | You ran an old build in `dist`. | Run `npm run build` again before `node dist/cli.js`. |
The .js extension in TypeScript imports surprises many people. The compiler does not rewrite import paths. What you write in the .ts file is exactly what appears in the .js file, and Node.js needs the real filename, which ends in .js. TypeScript understands that ./count.js refers to ./count.ts at type-check time.
Optional: pin the Node.js version
If the project requires a minimum Node.js version, say so in package.json:
{
"engines": { "node": ">=20" }
}Add the engines field next to the other top-level fields. npm warns when someone installs the package on an older Node.js version. It does not block the install unless the user sets engine-strict, so treat it as documentation that tooling can check.
What you have now
The project has a package that declares ESM, a compiler configured for Node.js, and build and test scripts. It also has a build that produces runnable JavaScript in dist. The next chapter explains each tsconfig.json option and what changes if you alter it.
Exercise
You add src/count.ts and import it from src/cli.ts with import { countText } from "./count". The build fails, or the compiled program fails at runtime with ERR_MODULE_NOT_FOUND. What is the fix, and why does the compiler not make this change for you?
Show answer
Change the import to "./count.js". In ESM under NodeNext, relative imports must name the file as Node.js will see it at runtime, which is the compiled .js file. The compiler does not rewrite import paths. It copies them unchanged into the output, and TypeScript resolves ./count.js to count.ts only while type-checking.
Exercise
A teammate installs typescript and @types/node with npm install (without --save-dev) and later asks whether that matters. Where do those packages end up in package.json, and why is devDependencies the better place?
Show answer
Without --save-dev they are added under dependencies. They belong in devDependencies because they are only needed to compile the code. The compiled JavaScript in dist does not import TypeScript, and type declarations are erased at compile time. Listing them as dependencies makes every user of the published tool install them for no reason.
Exercise
Running npm run build prints nothing and returns to the prompt. How do you confirm the build worked, and what would you check if node dist/cli.js then fails with Cannot use import statement outside a module?
Show answer
Check that dist/cli.js exists, for example with ls dist. For the error, open package.json and confirm it contains "type": "module". Without it, Node.js treats dist/cli.js as CommonJS and rejects the import syntax.