In this article, we are going to learn how to setup Typescript in NodeJS and create a simple web server using express package with typescript syntax.
Let's start!!!
- Create a folder named 'node-typescript-demo'
-
Open the above folder in VS code or any editor of your choice.
-
Run the following command to create a package.json file
npm --init y
-
Install typescript as a dev dependency by executing the following command.
npm i -D typescript
-
In order to test whether typescript is working or not, add a src folder -> create a file add.ts
-
Initialize a typescript configuration file.
-
Execute the command -> npx tsc --init
-
Now add a start script in package.json file to transpile the ts files to js files.
-
Now run the commnd ->npm start
-
Now let's test the generated js file in node by running the following command
node dist/add.js
-
Yay!!! We did it!!!
But every time we need to run the node command against the transpiled js files to get the output. Let's change this behaviour.
-
Let us install a package named ts-node as a dev dependency.
npm i -D ts-node
ts-node allows us to point to a Typescript file. It will run .ts, compile it and run it with Node.js.
-
Now let us change the start script command in package.json as
-
Now run the command -> npm start
Now let's create an express node server using typescript
-
Node.js packages are written in JavaScript and not Typescript. To get the type definitions for its packages, we need to install third-party packages called @types.
-
Install the types node definition by running the command -> npm install -D @types/node
-
Similarly install the express type definitions -> npm install -D @types/express
-
Add a file named server.ts in src folder.
-
Here we can see that the third party packages are imported using the import keyword. We are using typescript datatype against each variable/arguments, hence developers will get compile time errros.
-
Let's compare with the old way of coding express in node.
The required keyword is used to import the third party packages. The main thing is that we don't get any compilation error as we are using plain JavaScript code.
When developing an enterprise level application, it’s advisable to hook our project with watch parameters that will help us restart our server whenever we make and save changes to our code structure.
For that let's install a package named ts-node-dev. It watches .ts files, and whenever we make a change, it will restart the server for us.
Execute the command -> npm i -D ts-node-dev
Create a new script named 'development' in the scripts section of package.json
--respawn will restart the server whenever there is a change in any .ts files.
Finally, let's run the application by executing the command -> npm run development
Open the browser and go to http://localhost:5000
Finally, we have created a typescript node express server.
Happy Coding!!!
Note - Source code is uploaded.