node.jstypescriptvisual-studio-code

Setting VSCode to transpile typescript and start debugging with NodeJS with one F5 press?


Things seem unnecessarily complicated with VSCode+TypeScript+NodeJS. In a C# project in VS, just pressing F5 compiles the project and start debugging. How can I set VSCode do the same thing for TypeScript+NodeJS? What did I do wrong in the following?

I have searched Google and followed the top search result, but pressing F5 with the "test.ts" tab being the current tab seems doing nothing. It briefly shows the debugging tool bar at the top-right, and it disappears, with no output. I see no "test.js". If I press Ctrl+Shift+B, I see the "test.js", but all the output I get is

> Executing task: tsc -p c:\......\tsconfig.json <

Terminal will be reused by tasks, press any key to close it.

and not the output "101" I expected. The following is all the file contents in the directory:

test.ts

var a:number = 101;
console.log(a);

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true
    }
}

.vscode\launch.json (auto-created when I cliekd the link)

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "preLaunchTask": "tsc: build - tsconfig.json",
            "program": "${file}",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}

tasks.json (auto-created by selecting the menu)

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "problemMatcher": [
                "$tsc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "label": "tsc: build - tsconfig.json"
        }
    ]
}

Solution

  • That's what npm custom scripts are for

    In your package.json file:

    "scripts": {
    "start": "tsc && node test.js"
    }
    

    Then you can run npm run start where start is the name of the script. You may want to have several scripts, one for each use case

    With some npm scripts in your package.json file, if you try to debug a Node.js session on Visual Studio Code it will prompt you which script you want to use and it will run with just pressing F5.