Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Code compile on save

People also ask

Can you compile code in Visual Studio Code?

Open your C++ code file in Text Editor, then use shortcut Ctrl+Alt+N , or press F1 and then select/type Run Code , or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

How do I get Visual Studio to auto save code?

The easiest way to turn on Auto Save is with the File > Auto Save toggle that turns on and off save after a delay. For more control over Auto Save , open User or Workspace settings and find the associated settings: files.


May 2018 update:

As of May 2018 you no longer need to create tsconfig.json manually or configure task runner.

  1. Run tsc --init in your project folder to create tsconfig.json file (if you don't have one already).
  2. Press Ctrl+Shift+B to open a list of tasks in VS Code and select tsc: watch - tsconfig.json.
  3. Done! Your project is recompiled on every file save.

You can have several tsconfig.json files in your workspace and run multiple compilations at once if you want (e.g. frontend and backend separately).

Original answer:

You can do this with Build commands:

Create a simple tsconfig.json with "watch": true (this will instruct compiler to watch all compiled files):

{
    "compilerOptions": {
        "target": "es5",
        "out": "js/script.js",
        "watch": true
    }
}

Note that files array is omitted, by default all *.ts files in all subdirectories will be compiled. You can provide any other parameters or change target/out, just make sure that watch is set to true.

Configure your task (Ctrl+Shift+P -> Configure Task Runner):

{
    "version": "0.1.0",
    "command": "tsc",
    "showOutput": "silent",
    "isShellCommand": true,
    "problemMatcher": "$tsc"
}

Now press Ctrl+Shift+B to build the project. You will see compiler output in the output window (Ctrl+Shift+U).

The compiler will compile files automatically when saved. To stop the compilation, press Ctrl+P -> > Tasks: Terminate Running Task

I've created a project template specifically for this answer: typescript-node-basic


If you want to avoid having to use CTRL+SHIFT+B and instead want this to occur any time you save a file, you can bind the command to the same short-cut as the save action:

[
    {
        "key": "ctrl+s",          
        "command": "workbench.action.tasks.build" 
    }
]

This goes in your keybindings.json - (head to this using File -> Preferences -> Keyboard Shortcuts).


If pressing Ctrl+Shift+B seems like a lot of effort, you can switch on "Auto Save" (File > Auto Save) and use NodeJS to watch all the files in your project, and run TSC automatically.

Open a Node.JS command prompt, change directory to your project root folder and type the following;

tsc -w

And hey presto, each time VS Code auto saves the file, TSC will recompile it.

This technique is mentioned in a blog post;

http://www.typescriptguy.com/getting-started/angularjs-typescript/

Scroll down to "Compile on save"


Write an Extension

Now that vscode is extensible, it is possible to hook into the on save event via an extension. A good overview of writing extensions for VSCode can be found here: https://code.visualstudio.com/docs/extensions/overview

Here's a simple example that just calls echo $filepath and outputs stdout in a message dialogue:

import * as vscode from 'vscode';
import {exec} from 'child_process';

export function activate(context: vscode.ExtensionContext) {

    vscode.window.showInformationMessage('Run command on save enabled.');

    var cmd = vscode.commands.registerCommand('extension.executeOnSave', () => {

        var onSave = vscode.workspace.onDidSaveTextDocument((e: vscode.TextDocument) => {

            // execute some child process on save
            var child = exec('echo ' + e.fileName);
            child.stdout.on('data', (data) => {
                vscode.window.showInformationMessage(data);
            });
        });
        context.subscriptions.push(onSave);
    });

    context.subscriptions.push(cmd);
}

(Also referenced on this SO question: https://stackoverflow.com/a/33843805/20489)

Existing VSCode Extension

If you want to just install an existing extension, here is one that I wrote available in the VSCode gallery: https://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave

Source code is available here: https://github.com/emeraldwalk/vscode-runonsave/blob/master/src/extension.ts


I have struggled mightily to get the behavior I want. This is the easiest and best way to get TypeScript files to compile on save, to the configuration I want, only THIS file (the saved file). It's a tasks.json and a keybindings.json.

enter image description here