Getting Started- Express.js with Typescript
Getting Started- Express.js with Typescript | How to set up express.js and typescript project
Overview
In this article we will be learning about, how to set up TypeScript and Express.js project. This will involve few step to do it. I'm sure that you have already downloaded Node.js in your system.
1. Initialize Node.js Project:
If you haven't already, create a new directory for your project and initialize a new Node.js project using npm or yarn but in this tutorial we will be using npm to manage our dependencies. Open your terminal and follow the steps.
mkdir my-express-app
cd my-express-app
npm init -y
Above 3 command will help you to create a node.js project
2.Install Dependencies:
Install all dependencies that is required to build your node.js/express application. please follow the steps.
npm install express typescript @types/node @types/express
express
: The Express.js framework.typescript
: TypeScript compiler.@types/node
: TypeScript definitions for Node.js.@types/express
: TypeScript definitions for Express.js.
3.Create a tsconfig.json:
Create a TypeScript configuration file (tsconfig.json
) in the root directory of your project. This file specifies options for the TypeScript compiler.
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*"]
}
Please see the above json configuration that is required for our application.
4.Write Express Application Code in TypeScript:
Create your Express application code using TypeScript syntax. For example, in src/index.ts
:
import express, {Request, Response} from "express";
import coockieParser from "cookie-parser";
const PORT = 5000;
connectDB();
const app = express();
app.use(coockieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req:Request, res:Response ) => {
res.send('Hello World!');
});
app.listen(PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
});
Now you have created your first Typescript/Express.js server
5.Compile TypeScript to JavaScript:
Add the following script to your package.json
to compile TypeScript code to JavaScript using tsc
(the TypeScript compiler).
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "./src/index.ts",
"scripts": {
"start": "tsc && node ./dist/index.js",
},
"author": "",
"license": "MIT",
"dependencies": {
"express": "^4.18.2",
"@types/express": "^4.17.21",
"@types/node": "^20.10.5",
},
6.Run Your Express App:
Now, you can start your Express application using the script defined in package.json
.
npm start
Your Express app should now be running and accessible at http://localhost:3000
.
7.Bonus Tips
You can check their official website for more information here