DEV Community

keshav Sandhu
keshav Sandhu

Posted on

Converting any JS project to TS backend

First step if you are setting up from scratch


✅ 1. Initialize Your Node.js Project

bash
npm init -y

Creates a package.json file.


Conversion start now

✅ 2. Install TypeScript and Types for Node

bash
npm install --save-dev typescript @types/node

  • typescript: the TypeScript compiler
  • @types/node: type definitions for Node.js (so fs, path, etc. work)

✅ 3. Initialize TypeScript Config

bash
npx tsc --init

This generates a tsconfig.json. You can use the default, but you might want to tweak a few settings.

Recommended tsconfig.json tweaks:

jsonc
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src"]
}


✅ 4. Create Your Project Structure

bash
mkdir src
touch src/index.ts

Add a simple example in src/index.ts:

ts
const greet = (name: string) => {
console.log(Hello, ${name}!);
};

greet("TypeScript");


✅ 5. Compile TypeScript

bash
npx tsc

This compiles your TypeScript to JavaScript in the dist folder.


✅ 6. Run the Compiled JavaScript

bash
node dist/index.js


🔁 Optional: Add NPM Scripts

Edit package.json to make your workflow easier:

json
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsc --watch"
}

Now you can run:

bash
npm run build # Compile
npm start # Run
npm run dev # Watch and recompile on changes


🧪 Optional: Use ts-node to Run TS Directly (without compiling)

Install it:

bash
npm install --save-dev ts-node

Run TypeScript directly:

bash
npx ts-node src/index.ts


Top comments (0)