This guide helps you set up a Node.js Express project with TypeScript from scratch.
Run the following command to create a package.json
file:
npm init -y
Install Express and its required packages:
npm install express
Install TypeScript and development dependencies:
npm install --save-dev typescript ts-node @types/node @types/express
Install DotEnv for environment variables from a .env file
npm install dotenv
Run the following command to generate a tsconfig.json
file:
npx tsc --init
Modify tsconfig.json
with the following settings:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true
}
}
Create a src/index.ts
file and add:
import express from "express";
const app = express();
Use ts-node
to run the TypeScript server:
npx ts-node src/index.ts
Alternatively, compile and run:
npx tsc
node dist/index.js
Modify package.json
to add the following script:
"scripts": {
"dev": "ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
Now, you can start the server in development mode using:
npm run dev
Run the following command to install Jest and required packages:
npm install --save-dev jest ts-jest @types/jest supertest @types/supertest
Configure Jest
Initialize Jest with TypeScript support:
npx ts-jest config:init
Run Tests
npm test
- Express: A minimal and flexible web application framework for Node.js.
- TypeScript: A superset of JavaScript that adds static typing and advanced language features.
- ts-node: A TypeScript execution environment for Node.js.
- @types/express: TypeScript declaration files for Express.
You have successfully set up an Express.js server with TypeScript. 🎉