Compile Visual Studio Code when saving

How to configure Visual Studio code to compile typescript files when saving?

I see that you can configure the task to create a file in focus using ${file} as an argument. But I would like this to be done when saving the file.

+138
typescript visual-studio-code
May 01 '15 at
source share
14 answers

May 2018 update:

Starting in May 2018, you no longer need to create tsconfig.json manually or configure tsconfig.json tasks.

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

You can have several tsconfig.json files in your workspace and run several compilations at the same time if you want (for example, frontend and backend separately).

Original answer:

You can do this with the Build commands:

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

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

Please note that the 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 watch 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 the compiler output in the output window ( Ctrl + Shift + U ).

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

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

+180
May 19 '15 at 7:39
source share

If you want to avoid using CTRL + SHIFT + B and instead want it to happen anytime you save the file, you can attach the command to the same abbreviation as the save action

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

This applies to your keybindings.json - (go to this with File -> Preferences -> Shortcut).

+35
Jul 15 '15 at 20:44
source share

If you press Ctrl + Shift + B , you can enable "Auto Save" (File> Auto Save) and use NodeJS to view all the files in your project and run TSC automatically.

Open Node.JS command prompt, replace the directory in the project root folder and enter the following:

 tsc -w 

And hey presto, every time VS Code automatically saves a file, TSC will recompile it.

This method is mentioned in a blog post;

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

Scroll down to Compile on Save

+20
Aug 03 '15 at 19:07
source share

Burn extension

Now that vscode is extensible, you can connect to the save event through the extension. A good overview of writing extensions for VSCode can be found here: https://code.visualstudio.com/docs/extensions/overview

Here is a simple example that simply calls echo $filepath and displays stdout in the message dialog:

 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 by this SO question: https://stackoverflow.com/a/167185/ )

Existing VSCode Extension

If you just want to install an existing extension, here is what I wrote 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

+6
Nov 27 '15 at 21:54
source share

I fought very hard to get the behavior I want. This is the easiest and best way to get TypeScript files to compile when saving, to the configuration I want, only THIS file (saved file). These are the .json and keybindings.json tasks.

enter image description here

+6
Dec 04 '15 at 17:50
source share

Instead of creating a single file and linking Ctrl + S to run this assembly, I would recommend running tsc in view mode using the following tasks.json file:

 { "version": "0.1.0", "command": "tsc", "isShellCommand": true, "args": ["-w", "-p", "."], "showOutput": "silent", "isWatching": true, "problemMatcher": "$tsc-watch" } 

This will create the whole project and then restore the files that will be saved no matter how they are saved (Ctrl + S, auto save, ...)

+5
May 30 '16 at 9:04 a.m.
source share

I implemented compilation with persistence using the gulp task using gulp-typescript and incremental build. This allows you to control compilation no matter what you want. Pay attention to my tsServerProject variable, in my real project I also have tsClientProject, because I want to compile client code without the specified module. As I know, you cannot do this with code.

 var gulp = require('gulp'), ts = require('gulp-typescript'), sourcemaps = require('gulp-sourcemaps'); var tsServerProject = ts.createProject({ declarationFiles: false, noExternalResolve: false, module: 'commonjs', target: 'ES5' }); var srcServer = 'src/server/**/*.ts' gulp.task('watch-server', ['compile-server'], watchServer); gulp.task('compile-server', compileServer); function watchServer(params) { gulp.watch(srcServer, ['compile-server']); } function compileServer(params) { var tsResult = gulp.src(srcServer) .pipe(sourcemaps.init()) .pipe(ts(tsServerProject)); return tsResult.js .pipe(sourcemaps.write('./source-maps')) .pipe(gulp.dest('src/server/')); } 
+2
Jul 31 '15 at 7:01
source share

Choose Settings β†’ Workspace Options and add the following code. If you have hot restart enabled, the changes are immediately reflected in the browser

 { "files.exclude": { "**/.git": true, "**/.DS_Store": true, "**/*.js.map": true, "**/*.js": {"when": "$(basename).ts"} }, "files.autoSave": "afterDelay", "files.autoSaveDelay": 1000 } 
+1
Apr 25 '16 at 12:15
source share

I can say that with the latest version of TypeScript 1.8.X and 1.0 of Visual Studio code, the technique I showed is out of date. Just use tsconfig.json at the root level of your project, and everything works automatically to check the syntax. Then use tsc -w on the command line to automatically view / recompile. It will read the same tsconfig.json file for ts compilation options and settings.

 // tsconfig.json { "compilerOptions": { "module": "amd", "target": "ES5", "noImplicitAny": false, "removeComments": true, "preserveConstEnums": true, "inlineSourceMap": true }, "exclude": [ "node_modules" ] } 
+1
May 09 '16 at 14:10
source share
+1
May 29 '16 at 20:39
source share

updated

In your tsconfig.json

 "compileOnSave": true, // change to true 

if the problem persists, change any route, return it back and save the application. It will start compiling i.e.

 const routes: Routes = [ { path: '', // ie remove , (comma) and then insert and save, it'll compile component: VersionsComponent } ] 

Hope this helps someone. Although this is not a permanent solution, it works until you get the best solution.

0
Jul 11 '18 at 7:56
source share

I tried the above methods, but mine stopped autocompiling when I wanted to, because the maximum number of files to view exceeded the limit.

run cat/proc/sys/fs/inotify/max_user_watches .

if it shows fewer files, including node_modules, open the /etc/sysctl.conf file with superuser privileges and add

fs.inotify.max_user_watches=524288 to file and save

run the cat command again to see the result. It will work! with hope!

0
Mar 05 '19 at 5:44
source share

An extremely simple way to automatically compile when saving is to enter the following into the terminal:

tsc main --watch

where main.ts is the name of your file.

Please note that this will only work as long as this terminal is open, but it is a very simple solution that can be launched while editing the program.

0
Jun 17 '19 at 13:56 on
source share

The answer is for VisualStudio, not VisualStudio-Code:

  • Set the Script -Extension type for VisualStudio:
  • Go to Tools-> Options-> Text Editor β†’ (JavaScript / *) TypeScript β†’ Project
  • Activate 'Compile on Safe' β†’ Automatically compile TypeScript files that are not part of Project

* VS2017

-3
May 11 '17 at 7:43
source share



All Articles