Step-by-Step: Setting up a Node.js (Express) Server in TypeScript
TypeScript is really gaining traction these days and although most node.js server code is written in JavaScript, TypeScript is finally invading into this territory too.
Recently, i wrote a new node.js server and decided to write it in TypeScript. I referenced several articles and thought of sharing the exact steps that can help someone to quickly setup a node.js server in TypeScript. So, here we go…
- Have a working node.js server in JavaScript (with express, express-session etc. packages already installed). For this article, let’s assume that the server code is in ‘./src’ directory and the output directory is ‘./dist’.
2. Install the following packages:
$ npm i typescript ts-node-dev — save-dev
3. Install the following types so that TypeScript knows about these:
$ npm i @types/express @types/express-session @types/node @types/request — save-dev
4. Initialize typescript config file (tsconfig.json):
$ npx tsc — init
This will create tsconfig.json file. Update the compiler options in the file as desired.
5. Optional step: add linting support:
$ npm i tslint — save-dev
6. Add the following scripts in package.json:
“tsc”: “tsc”,
“dev”: “ts-node-dev — respawn — transpileOnly ./src/index.ts”,
“prod”: “tsc && node ./dist/index.js”,
7. To run the server in watch mode in development environment, run the following command:
$ npm run dev
8. Similarly, to run the server in production environment, run the following command:
$ npm run prod