Node.js - use TypeScript instead of JavaScript in VS Code
In this article, we would like to show you how to use TypeScript instead of JavaScript in VS Code for Node.js projects.
Note:
You can download the github project for the article here - dirask-tutorials · GitHub
If you have already installed TypeScript compiler globally, you can skip this step.
xxxxxxxxxx
npm install -g typescript
Note:
Go to this article if you want to know more about TypeScript installation process.
xxxxxxxxxx
{
"compilerOptions": {
"target": "ES5", // JavaScript version to which we map TypeScript
"module": "CommonJS", // we will use the module mechanism in Node.js, i.e. 'require'
"moduleResolution": "Node", // process that compiler uses to figure out what an import refers to
"baseUrl": "./src", // optional localization of the folder with source files during modules mapping
"outDir": "./dist", // the output folder where we get the built js files
"sourceMap": true // used to enable debbuging TypeScript in Node.js and VS Code
},
"include": [
"src/**/*.ts" // describes what files to import for compilation - searching for .ts files in whole directory
]
}
Create .vscode directory with launch.json file.
launch.json:
xxxxxxxxxx
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "My Application", // configuration name
"program": "dist/index.js" // executable file of the entire application (compiled index.ts to js)
}
]
}
Build the application with the following command:
xxxxxxxxxx
tsc --build
Note:
After this command the dist/ directory is created. Go to the Project Structure section to see the screenshot.
Run the application using:
xxxxxxxxxx
node ./dist/index.js
TypeScript compiler during development automatically recompiles files changed by developer. You can run application in development mode with the following command:
xxxxxxxxxx
tsc --watch --project .
In this section we present how debugging of the index.ts
file looks like after building and running our application.
This section presents the structure of example project that we created for the article.
TypeScript installation and configuration:
Debugging Node.js app from VS Code: