TypeScript is a game-changer for Node.js development, bringing type safety and modern tooling to your JavaScript codebase. In this guide, I’ll walk you through the exact steps I used to migrate my Node.js project to TypeScript—no prior TypeScript experience required!
1. Install TypeScript and Type Definitions
First, install TypeScript and the Node.js type definitions as development dependencies:
npm install --save-dev typescript @types/node2. Initialize TypeScript Configuration
Generate a tsconfig.json file with the following command:
npx tsc --initThis creates a base TypeScript configuration file in your project root.
3. Update tsconfig.json
Open your tsconfig.json and add or update these important fields:
{
"include": ["**/*.ts"],
"exclude": ["node_modules"],
"compilerOptions": {
"outDir": "./dist"
// ...other options
}
}-
includetells TypeScript to compile all.tsfiles. -
excludepreventsnode_modulesfrom being compiled. -
outDirspecifies where the compiled JavaScript will go.
4. Rename Your Files to .ts
Rename your existing .js files to .ts. For example:
mv server.js server.tsDelete the old .js files to avoid confusion.
5. Compile TypeScript Files
Now, compile your TypeScript files:
npx tscThis will generate JavaScript files in the dist directory (as specified by outDir).
6. Run the Compiled JavaScript
Run your app using Node.js, pointing to the compiled entry file in dist:
node dist/server.jsOr whatever your entry point is.
7. (Optional) Update npm Scripts
For convenience, add a script to your package.json:
"scripts": {
"build": "npx tsc",
"start": "node dist/server.js"
}Now you can run:
npm run build
npm startConclusion
That’s it! You’ve successfully added TypeScript support to your Node.js project. Enjoy better type safety, editor autocompletion, and more robust code!
If you found this guide helpful, follow me for more tips on JavaScript, TypeScript, and Node.js development.