Step by step using Typescript (TS) in Express (Node.js) Project
--
In this tutorial, you will learn how to use Typescript(TS) in Express (Node.js) project.
Requirements:
- Basic knowledge in Typescript (TS), Node.js and Express
- Having a Node version from v12 upwards, including Node 12.
1. Set up the project
The first step is to create a directory for the project and initialise it. Run the following commands to create an empty directory called express-nodejs-ts
, and change the current directory to it:
mkdir express-nodejs-ts
cd express-nodejs-ts
Now that you are in the express-nodejs-ts
directory, you have to initialise the Node project. To do so, run the following command:
npm init -y
Using the -y
flag in the above command generates the package.json
file with the default values. Instead of adding information like the name and description of the project ourselves, npm initialises the file with default values.
The project is initialised, and thus you can move to the next section — adding the project dependencies.
2. Add dependencies
The next step is to add the project dependencies (Express and Typescript) by running the following commands:
npm install express
npm install typescript ts-node @types/node @types/express --save-dev
Why save everything Typescript-related as devDependencies
? Even though you write the code using Typescript, the code gets compiled back to vanilla JavaScript. Typescript is not needed per se to run the application. Thus, since Typescript is used only by developers, it's saved as a dev dependency.
Moving forward, your package.json
should look as follows after installing all the dependencies:
{
"name": "express-nodejs-ts",
"version": "1.0.0",
"description": "Express project with TypeScript",
"main": "index.js",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"@types/express": "^4.17.9",
"@types/node": "^14.14.20",
"ts-node": "^9.1.1",
"typescript": "^4.1.3"
},
"scripts": {
"test": "echo \"Error: no test…