We know how to set up an express server with JavaScript, but some of us find it difficult to set up with TypeScript ๐ช.
C'mon man, let's grab a cup of coffee, hot one โ
Here are some steps in which an express server can be set up TypeScript :
Create a new nodejs project using
npm init -y
Install TypeScript and required dependencies using
npm install --save-dev typescript ts-node nodemon
Initialize TypeScript by running
tsc --init
. This will create atsconfig.json
file in the root directory of your project.Modify the
tsconfig.json
in the "compilerOptions", with the following options:"module": "NodeNext"
- Specifies the module code generation method."moduleResolution": "node"
- Helps the compiler figure out what an import refers to. The value node mimics the Node module resolution mechanism."baseUrl": "src"
- Specifies the base directory for resolving non-relative module names."outDir": "dist"
- Specifies the output directory for compiled files."sourceMap": true
- Generate source maps for better debugging."noImplicitAny": true
- Raises an error when a variable or parameter has an implicitany
type."esModuleInterop": true
- Enables compatibility with libraries that useexport=
."include": ["src/**/*"]
- Specifies the files or directories to include in the compilation process.
Create a file called
nodemon.json
with the following configuration:{ "watch": ["src"], "ext": ".ts,.js", "exec": "ts-node ./src/index.ts" }
This tells
nodemon
to watch thesrc
directory for changes with.ts
and.js
extensions and execute theindex.ts
file usingts-node
.Create a new folder called
src
and add anindex.ts
file inside it. This file will contain the code for your Express.js server.Install
express
and other required middleware usingnpm install express body-parser cookie-parser compression cors
.Install type definitions for the middleware using
npm install @types/express @types/body-parser @types/cookie-parser @types/compression @types/cors
.Modify the
scripts
section inpackage.json
to include the following:"scripts": { "start": "nodemon", "test": "echo \"Error: no test specified\" && exit 1" }
This tells
npm
to runnodemon
when you runnpm start
.Add the code for your Express.js server in src/index.ts. Let's build a simple server
// Import necessary libraries and modules import express, {Application, Request, Response, NextFunction} from 'express'; import bodyParser from 'body-parser'; import cookieParser from 'cookie-parser'; import compression from 'compression'; import cors from 'cors'; // Create an instance of the Express application const app: Application = express(); // Use middleware to parse request bodies, cookies, compress response data, and enable CORS app.use(bodyParser.json()); app.use(cookieParser()); app.use(compression()); app.use(cors()); // Define a route handler for the root path app.get('/', (req: Request, res: Response) => { res.send('Hello World!'); }); // Define an error handling middleware app.use((err: Error, req: Request, res: Response, next: NextFunction) => { console.log(error); next(); }); // Set the port number for the server const PORT: number = process.env.PORT || 3000; // Start the server and listen for incoming requests on the specified port app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Run your server using
npm start
.
Yay! ๐ฅณ๐ฅณ .We have successfully set up an express server with TypeScript.
Have a nice day creating a bug less environment for your APIs ๐