OK, you fall in love with typescript, and now you really want to use it in your new express project.
A common approach in using typescript in node project
Start the new node project by running this command in your directory via the terminal.
1. Create a new node project, with a package.json file
npm init
This will generate a new package.json file. Let me show mine:
{
"name": "friend-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Teerasej Jiraphatchandej",
"license": "ISC"
}
2. Add packages for typescript
So we want to set up this project for us to use typescript in development. We add 2 packages as devDependencies
:
npm i -D @types/node
npm i -D typescript
Here we go. We have package.json file similar to the one below:
{
"name": "friend-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Teerasej Jiraphatchandej",
"license": "ISC",
"devDependencies": {
"@types/node": "^17.0.29",
"typescript": "^4.6.3"
},
}
3. Add tsconfig.json
OK, let's create another file: tsconfig.json at the root of the project's directory. This file will tell how would typescript's compiler work:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist"
},
"lib": ["es2015"]
}
5. Let compile and run
from this point, you can use the following command in the terminal to compile all tsc
files in project into /dist
directory (as you set it up in tsconfig.json: outDir)
tsc
and you can run your compiled code with
node dist/<file name>.js
6. Done, but you can add more ease
Execute 2 commands repeatedly will take out our energy. You can use the script section in package.json to create a shortcut
{
...
"scripts": {
"start": "tsc && node dist/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
...
}
After save the package.json file, you can compile and run your project with one simple command:
npm run start
Top comments (2)
You should also install @types/node if you are going to use nodejs built in packages because node does not come with type declarations by default
Thank you for your suggestion, content updated!