Express JS using Typescript and visual stdio code

0
40

Introduction

Express is a light-weight web application framework to help organize your web application into an MVC architecture on the server side. TypeScript enables us to develop a solid web applications using Express on Node.js

Prerequisite

  • Node JS
  • Visual Studio Code

Create a folder EJS and open the folder EJS in visual studio code

Create file called package.json to install the required packages.

Package.json 

{ "name": "ejsts", "version": "1.0.0", "description": "Express", "scripts": { "start": "tsc -p ./src && concurrently \"tsc -w -p ./src\" \"nodemon build/server/main.js\"" }, "keywords": [ "typescript" ], "dependencies": { "@types/express": "^4.0.32", "@types/body-parser": "^0.0.32", "@types/node": "^6.0.48", "agentkeepalive": "3.1.0", "async": "2.1.5", "body-parser": "^1.17.1", "express": "^4.15.2", "express-ntlm": "2.1.5", "httpntlm": "1.7.5", "ts-loader": "2.0.1", "ts-node": "1.2.1", "tslint": "^4.0.0", "typescript": "^2.1.6" }, "devDependencies": { "concurrently": "^3.1.0", "nodemon": "^1.11.0" } }

"start": "tsc -p ./src && concurrently \"tsc -w -p ./src\" \"nodemon build/server/main.js\"" – This line will check for the changes in the code and rebuild the application. 

Configure the typescript by adding tsconfig.json file. (to configure and inform the compiler the typescript file under the folder src) tsconfig.json

 { "compilerOptions": { "target": "es6", "module": "commonjs" }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules" ] }

Open the command prompt and navigate to the directory and type command npm install

Create a folder src and add the following files. Add the tsconfig.json file to configure the output path, module and target of ES Version.

 tsconfig.json { "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es6", "dom"], "mapRoot": "../build/server", "module": "commonjs", "moduleResolution": "node", "outDir": "../build/server", "sourceMap": true, "target": "es6", "typeRoots": [ "../node_modules/@types" ] } }

Customer.controller.ts

 import { Router, Request, Response, NextFunction } from 'express'; export class CustomerController { public static route: string = '/customers'; public router: Router = Router(); constructor() { this.router.get('/customers', this.getCustomers); } private getCustomers(req: Request, res: Response, next: NextFunction) { let customers = [{ customerId: 1001, customerName: 'suresh' }, { customerId: 1001, customerName: 'suresh' }] res.status(200).send(customers); } }

Main.ts

import { Router, Express } from 'express'; import * as express from 'express'; import * as http from 'http'; import { json, urlencoded } from 'body-parser'; import { CustomerController } from './controller/customer.controller'; export class Main { public app: Express; private port: number = 2000; constructor() { this.app = express(); this.configureMiddleware(this.app); this.configureRoutes(this.app); } private configureMiddleware(app: express.Express) { app.use(json()); app.use(urlencoded({ extended: true })); } private configureRoutes(app: express.Router) { app.use(CustomerController.route, new CustomerController().router) } public run() { let server = http.createServer(this.app); server.listen(this.port); server.on('error', this.onError); console.log('server started at ' + this.port); } private onError(error) { let port = this.port; if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } } new Main().run();

To execute the express JS type the command npm start, it will execute the file from build/server/main.js. As we have configure that path in package.json and tsconfig.json Open the browser and type the url http://localhost:2000/customers

LEAVE A REPLY