Setting up TypeScript in Node.js Project

The best way to set up TypeScript in a Node.js project (save this for future) While starting with TypeScript in Node.js, the setup steps can feel confusing if you don't know why each command is used. Here's the clean workflow I follow. 1. Initialize the project npm init -y This creates a package.json file to manage dependencies and scripts. 2. Install TypeScript as a dev dependency npm i typescript --save-dev Why not install it as a normal dependency? Because TypeScript is only a development tool. Node.js and browsers run JavaScript, not TypeScript. Installing it as a dev dependency keeps the production build smaller. 3. Create the TypeScript configuration npx tsc --init This generates tsconfig.json which controls how TypeScript compiles the project. 4. Organize your project structure Inside tsconfig.json uncomment: "rootDir": "./src" "outDir": "./dist" Now all your TypeScript code will live inside ./src and the compiled JavaScript will go into ./dist. This keeps the project structure clean. 5. Create a .gitignore npx gitignore Node This prevents committing unnecessary files like node_modules and build outputs. 6. Compile TypeScript npx tsc This converts .ts files into .js files so Node.js can execute them. The problem: Every time you change the code, you would have to compile TypeScript again manually. 7. To solve this we can use tsc-watch. npm i tsc-watch -D 8. Update scripts in package.json "scripts": { "dev": "tsc-watch --onSuccess "node dist/main.js"" } 9. Run the project npm run dev Now whenever you save a file: TypeScript automatically compiles and Node runs the updated code. Commands summary: npm init -y npm i typescript --save-dev npx tsc --init (uncomment rootDir and outDir in tsconfig.json) npx gitignore Node npm i tsc-watch -D (update scripts in package.json) npm run dev If you're learning Node.js with TypeScript, this setup will save you a lot of time. #nodejs #typescript #backenddevelopment #javascript #webdevelopment #chaicode #chaiaurcode Hitesh Choudhary

  • text

To view or add a comment, sign in

Explore content categories