Create a server with Nodemon + Express + Typescript

Juan Sanchez
Node Fun!
Published in
3 min readNov 18, 2018

Typescript is powerful transpiler for javascript designed by microsoft and using in projects for Angular applications in this time I going to tech you how create a application and debug it in visual studio code.

  1. Basic Setup

First let’s start out in an empty directory. I going to create a new folder call typescript-nodejs and after initialize npm.

$ npm init
$ mkdir src && touch src/server.ts

Next let’s install all dependencies:

$ npm install express --save
$ npm install --save-dev typescript @types/node eslint eslint-plugin-import nodemon ts-node

@types/node : Is a plugin than help us to resolve node names

eslint eslint-plugin-import: help us to resolve import issues than we can have.

nodemon: This plugin avoid us than periodically we have reloading application.

ts-node: Allow us to run typescript files without transpile javascript to plain text.

Now let’s create our server in server.ts:

import * as express from "express";const app = express();app.get("/", (req, res) => {    res.send("Hello World")})const PORT = process.env.PORT || 3000;app.listen(PORT, () => {     console.log(`Server is running in http://localhost:${PORT}`)})

ultimately, let’s create tsconfig.json for add typescript settings:

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

2. Setup our package.json and add scripts

First let’s to define scripts:

"scripts": {"start": "node --inspect=5858 -r ts-node/register ./src/server.ts","start:watch": "nodemon","build": "tsc"}

“start”: “node — inspect=5858 -r ts-node/register ./src/server.ts”: Runs and enable us our server:

— inspect=5858: Enable us 5858 port for debugging our project.

-r ts-node/register ./src/server.ts: Runs our typescrypt file.

“start”: “nodemon”: This runs our nodemon process but first we need to add this settting to our package:

"nodemonConfig": {"ignore": ["**/*.test.ts","**/*.spec.ts",".git","node_modules"],"watch": ["src"],"exec": "npm start","ext": "ts"},

basically each time the nodemon detect a new change in the folder src run in my package script npm start. (see more settings here)

“build”: “tsc”: Take our tsconfig.json and generate a dist of our project.

3. Runs application

Now if you runs npm run start:watch you nodemon process and server start out:

And if runs npm run build generate us out dist folder:

4. Debug with vs code

Ultimately, We just enable auto Attach node process of vs code for start to debug our project:

command + shift + p

Now when runs npm run start:watch in our terminal automatically it will start to debug.

That’s all!

Thank you for reading this article and give a like 😎.

--

--