How to Setup a TypeScript + Node.js Project - A Straightforward Guide

Hey there fellow developers! Today, I want to walk you through the process of setting up a TypeScript project from scratch for Node.js. No fluff, no nonsense - just the essentials to get you up and running quickly!

First things first, make sure you have Node and npm installed on your machine and a code editor like Visual Studio Code.

Let's get started:

Step 1: Create a new folder for your project.

mkdir typescript-starter
cd typescript-starter

Step 2: Initialize the project and add TypeScript as a dev dependency.

npm init -y
npm install typescript --save-dev

Step 3: Install ambient Node.js types for TypeScript.

npm install @types/node --save-dev

Step 4: Create a tsconfig.json file to define TypeScript compiler options.

npx tsc --init --rootDir src --outDir build --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true

Your tsconfig.json should now look like this:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["es6"],
    "allowJs": true,
    "outDir": "build",
    "rootDir": "src",
    "strict": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

Step 5: Create a src folder and add your first TypeScript file (index.ts) with some code.

mkdir src
echo 'console.log("Hello world!");' > src/index.ts

Step 6: Compile your TypeScript code.

 npx tsc --init --rootDir src --outDir build --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true--noImplicitAny true

Your compiled JavaScript file will now be available at build/index.js.

Now let's add some useful configurations and scripts:

Step 7: Add hot-reloading for development using ts-node and nodemon.

npm install --save-dev ts-node nodemon

Create a nodemon.json config:

{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "npx ts-node ./src/index.ts"
}

or just run this command:

echo '{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "npx ts-node ./src/index.ts"
}' > nodemon.json

And add this script to your package.json:

"start:dev": "npx nodemon"

Now you can run your project in development mode with hot-reloading using:

npm run start:dev

Step 8: Create production builds with a build script.

npm install --save-dev rimraf

Add this script to your package.json:

"build": "rimraf ./build && tsc"

To build your project for production, simply run:

npm run build

Step 9: Add a production startup script.

"start": "npm run build && node build/index.js"

You can start your app in development mode with:

npm run start:dev

To start your app in production mode use:

npm start

And that's it! You now have a basic TypeScript + Node.js project up and running. You can further enhance this setup with testing and linting as needed.

Remember, keep it simple, stay focused, and keep on coding. Happy developing!"