Languages
[Edit]
EN

Node.js - use TypeScript instead of JavaScript in VS Code

0 points
Created by:
Romany-Welsh
382

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

1. Install TypeScript globally

npm install -g typescript

2. Create tsconfig.json file

{
    "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
    ]
}

3. Configuration for debugging Node.js applications in VS Code

Create .vscode directory with launch.json file.

launch.json:

{
    "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)
    }]
}

4. Build and run the application

Build the application with the following command:

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:

node ./dist/index.js

5. Monitor changes

Monitor the application for changes mode (such as nodemon) with the following command:

tsc --watch --project .

Debugging example

In this section we present how debugging of the index.ts file looks like after building and running our application.

Debugging.png

Project structure

This section presents the structure of example project that we created for the article.

Project.png

References

TypeScript installation and configuration:

  1. TypeScript - how to install tsc (TypeScript compiler) for Windows

  2. TypeScript - upgrade TypeScript compiler (tsc upgrade)

Debugging Node.js app from VS Code:

  1. VS Code - debug js file with Node.js

  2. VS Code - debug Express.js under Node.js server

  3. VS Code - debug with npm run

  4. TypeScript debugging with Visual Studio Code - Microsoft Docs 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join