Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup Visual Studio Code to transpile typescript on build and debug

I'm a long time (15+ years) Visual Studio user and am excited to learn both Typescript and the new leaner, meaner Visual Studio Code. I've been trying to setup VSCode like VS, where when you hit F5 it transpiles to Javascript and launches the debugger.

I've found posts that trigger it on save, or using another shortcut (run via tasks.json) - but I'm really surprised there isn't a way of doing this on such a fundamental command, unless I'm really missing something embarrassingly obvious.

At this point I'm just trying to use the "Hello World" greeter sample checked out directly from Microsoft, where it has a manual step of tsc --sourcemap greeter.ts. I just want that to happen automatically, like it does in VS, on any files that need transpiling before I start to run / debug.

Does anyone know how to do this? Thank you.

like image 721
user3147973 Avatar asked Sep 24 '16 17:09

user3147973


3 Answers

The short answer (in a new project directory) is:

  • Press Ctrl+Shift+B to Build your project in VSCode
  • If .vscode/tasks.json is not already configured, a message will give you the option to Configure Task Runner, press that button.
  • Choose one of the two predefined TypeScript options.
  • You can close the tasks.json window this opened up.

After having tried both TypeScript options, I prefer the ... in watch mode option. That way, after starting the background process with Ctrl+Shift+B once, incremental transpiles happen whenever a file is saved, making launching the program for debugging that much faster...

For more details, follow this link: http://code.visualstudio.com/docs/languages/typescript#_transpiling-typescript-into-javascript

If you want to generate a source map (a good idea), you need to setup tsconfig.json. The quick way to do that from VSCode is:

  • Press Ctrl+Shift+C to open up a command line window.
  • type the command tsc --init --sourceMap to set up a template tsconfig.json
  • type the command exit

Finally, if you want to use the source map while debugging, you need to generate and edit the .vscode/launch.json file. The quick way to do that is:

  • If .vscode/launch.json doesn't already exist, pressing F5 will prompt you to choose and environment. Choose Node.js.
  • Edit the generated file replacing all occurances of "sourceMaps": false with "sourceMaps": true.

I'm not sure why the defaults omit source maps, it currently seems like one of the most common bumps in the road for people starting to use VSCode + TypeScript.

like image 105
Burt_Harris Avatar answered Oct 25 '22 07:10

Burt_Harris


So, using help from responses here was the path of least resistance. After opening vscode, I:

  1. File -> Open Folder
  2. Created an empty sub-folder within my code directory called HelloWorld in this case
  3. Created a tsconfig.json file and copied the example from this article which is:
    {
        "compilerOptions": {
            "target": "es5",
            "module": "commonjs",
            "sourceMap": true
        }
    }
  4. Created a helloWorld.ts as directed by the same article, which is:
    class Startup {
    public static main(): number {
        console.log('Hello World');
        return 0;
        }
    }
    Startup.main();
  5. Hit F5 (to Debug) and VSCode asked me if I wanted a Node.js environment or a VSCode environment, I selected Node.js.
  6. It generated me a launch.json, where I did the following edits:
  7. Switched "program": "${workspaceRoot}/app.js", to "program": "${workspaceRoot}/helloWorld.js",
  8. Replaced the null in preLaunchTask to: "preLaunchTask": "tsc",
  9. Replaced the 3 instances of sourceMaps from false to true.
  10. Hit F5 again, VSCode pops up an info saying no task runner configured. I click configure and select TypeScript - Watch Mode.
  11. Put a breakpoint on a line in my ts file
  12. Hit F5 one last time and everything works!

So tsc compiler seems pretty slow, takes about 4-5 seconds to transpile on my 2 year old Win10 computer. I see the benefit of TypeScript - Watch Mode so it could it's transpiling as you hit Save. Otherwise, if you transpile everytime before you debug, it doesn't seem to detect whether it needs a transpile or not, so this is the ideal scenario that matches what Visual Studio developers are used to.

like image 9
user3147973 Avatar answered Oct 25 '22 05:10

user3147973


Essentially VS Code allows you to create tasks to automate development processes (cleaning files/folders, compiling, bundling, etc.) and also allows you to create environment configurations to run your project.

To have them work together the environment configuration allows specification of a preLaunchTask which will run the defined task before debugging. To create a workflow similar to Visual Studio you could create a compile task and run the task before the debugger by setting it as the preLaunchTask.

  • This article walks through the process of getting started with TypeScript for both express (web) and node.js apps.

Example running tsc (TypeScript compiler) before debugging

1.Create a tsconfig.json file in the root of your project with your choice of compile options.

Example tsconfig.json file (You may need to change the module setting to best suit your project. amd is typically a web project, commonjs is typically a node.js project but everyone's preference varies:

{
    "compilerOptions": {
        "target": "es6",
        "module": "amd",
        "sourceMap": true,
        "allowSyntheticDefaultImports": true
    },
    "exclude": [
        "node_modules",
        "bower_components",
        "jspm_packages",
        "tmp",
        "temp"
    ]
}

2.Create a launch.json file to run and debug your project and set the preLaunchTask to tsc.

The easiest way to do this is simply hit F5. The first time you run it will ask to "Select an environment", if you have already created a launch.json file and would like to start fresh, delete the file. For TypeScript I normally choose node.js which will allow you to run in process or within a web context with frameworks such as express.

Example launch.json file (this example is of an express app):

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/bin/www",
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": "tsc",
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "console": "internalConsole",
            "sourceMaps": false,
            "outDir": null
        }
    ]
}
like image 4
Jesse Johnson Avatar answered Oct 25 '22 07:10

Jesse Johnson