保存时编译 VisualStudio 代码

如何配置 VisualStudio 代码以在保存时编译打印脚本文件?

我看到有可能配置一个任务来使用 ${file}作为参数构建焦点文件。但是我希望在保存文件时执行此操作。

134291 次浏览

2018年5月更新:

自2018年5月起,您不再需要手动创建 tsconfig.json或配置任务运行程序。

  1. 在项目文件夹中运行 tsc --init以创建 tsconfig.json文件(如果您还没有这样的文件)。
  2. Ctrl + Shift + B在 VS Code 中打开任务列表并选择 tsc: watch - tsconfig.json
  3. 完成! 您的项目将在每个保存的文件上重新编译。

如果需要,您可以在工作区中放置多个 tsconfig.json文件,并且可以同时运行多个编译(例如,分别运行前端和后端)。

原答案:

您可以使用 Build 命令完成以下操作:

"watch": true创建一个简单的 tsconfig.json(这将指示编译器监视所有已编译的文件) :

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

请注意,省略了 files数组,默认情况下将编译所有子目录中的所有 *.ts文件。您可以提供任何其他参数或更改 target/out,只需确保 watch设置为 true

配置你的任务(Ctrl + Shift + P-> Configure Task Runner) :

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

现在按 Ctrl + Shift + B生成项目。您将在输出窗口(Ctrl + Shift + U)中看到编译器输出。

编译器在保存时会自动编译文件。要停止编译,请按 Ctrl + P-> > Tasks: Terminate Running Task

我已经为这个答案专门创建了一个项目模板: typescript-node-basic

如果希望避免使用 CTRL + SHIFT + B,而是希望在保存文件时发生这种情况,可以将命令绑定到与保存操作相同的快捷方式:

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

这将进入 keybindings.json-(使用 File-> Preferences-> Keyboard Shortcut 进入此目录)。

我使用 咕噜咕噜打字稿和增量构建实现了保存和吞吐任务的编译。这允许您随心所欲地控制编译。注意我的变量 tsServerProject,在我的实际项目中我也有 tsClientProject,因为我想编译没有指定模块的客户端代码。因为我知道你不能用 VS 代码做到这一点。

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/'));


}

如果按 Ctrl + 换挡 + B看起来很费力,你可以打开“自动保存”(文件 > 自动保存) ,使用 NodeJS 监视项目中的所有文件,并自动运行 TSC。

打开 Node.JS 命令提示符,将目录更改为您的项目根文件夹并键入以下内容;

tsc -w

很快,每次 VS 代码自动保存文件时,TSC 都会重新编译它。

在一篇博客文章中提到了这个技巧;

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

向下滚动到“保存时编译”

写一个扩展

既然 vscode 是可扩展的,就可以通过扩展连接到 on save 事件。在这里可以找到编写 VSCode 扩展的一个很好的概述: Https://code.visualstudio.com/docs/extensions/overview

下面是一个简单的例子,它调用 echo $filepath并在消息对话中输出 stdout:

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);
}

(在这个标准问题上也提到: Https://stackoverflow.com/a/33843805/20489

现有 VSCode 扩展

如果你只想安装一个现有的扩展,这里有一个我写的可在 VSCode 库: Https://marketplace.visualstudio.com/items/emeraldwalk

源代码可以在这里找到: Https://github.com/emeraldwalk/vscode-runonsave/blob/master/src/extension.ts

我为了得到我想要的行为付出了很大的努力。这是让 TypeScript 文件在保存时按照我想要的配置进行编译的最简单和最好的方法,只保存这个文件(保存的文件)。是 tasks.json 和 keybindings.json。

enter image description here

选择 首选项-> 工作区设置并添加以下代码,如果启用了热重新加载,则更改将立即反映在浏览器中

{
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/*.js.map": true,
"**/*.js": {"when": "$(basename).ts"}
},
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000
}

我可以说,在最新版本的 TypeScript 1.8.X 和 Visual Studio 代码1.0中,我展示的技术已经过时了。只需在项目的根级别使用 tsconfig.json,就可以自动进行语法检查。 然后在命令行上使用 tsc-w 自动监视/重新编译。它将读取相同的 tsconfig.json 文件中的选项和编译配置。

// tsconfig.json


{
"compilerOptions": {
"module": "amd",
"target": "ES5",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"inlineSourceMap": true
},
"exclude": [ "node_modules" ]
}

我建议使用以下 tasks.json 文件以监视模式启动 tsc,而不是构建单个文件并绑定 Ctrl + S 来触发该构建:

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

这将一次性构建整个项目,然后重新构建独立于如何保存而保存的文件(Ctrl + S,auto save,...)

第一步

在你的 tsconfig.json

"compileOnSave": true, // change it to true and save the application

如果问题仍然存在,那么应用 step-2

第二步

重新启动编辑器

如果仍然有问题没有解决,那么应用 step-3

第三步

更改任何路由,将其恢复并保存应用程序。它将开始编译。

const routes: Routes = [
{
path: '', // i.e. remove , (comma) and then insert it and save, it'll start compiling
component: MyComponent
}
]

尝试上述方法,但我的停止自动编译时,它觉得像它,由于 最多可观看的文件已经超过了限制。

运行 cat /proc/sys/fs/inotify/max_user_watches命令。

如果包含 node _ module 的文件数较少,那么打开该文件 根权限中的 /etc/sysctl.conf并附加

fs.inotify.max_user_watches=524288保存到文件中

再次运行 cat 命令查看结果。它将工作! 希望!

在保存时自动编译的一种极其简单的方法是在终端中键入以下内容之一:

tsc main --watch // autosave `main.ts`
tsc -w // autosave all typescript files in your project

注意,这只会在终端打开时运行,但它是一个非常简单的解决方案,可以在编辑程序时运行。

我在. VSCode/tasks.json 中使用运行在文件夹上的自动任务(应该可以使用 VSCode > = 1.30)

{
"version": "2.0.0",
"tasks": [
{
"type": "typescript",
"tsconfig": "tsconfig.json",
"option": "watch",
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "shared"
},
"isBackground": true,
"runOptions": {"runOn": "folderOpen"},
"problemMatcher": [
"$tsc-watch"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

如果这仍然不能在项目文件夹打开尝试 Ctrl + shift + P 和任务: 管理文件夹中的自动任务,并在主项目文件夹或正在运行的文件夹中选择“允许自动任务在文件夹中”。

您需要增加手表限制来修复保存时的重新编译问题,打开终端并输入以下两个命令:

sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system

要使更改在重新启动后仍然持久,请运行以下命令:

echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system

这里有各种有效的答案,但不一定适用于每个不同的 TS 编译器 env。也许跟踪可以在全球范围内起作用。

第一步

在您的项目根文件夹下有一个最小的 tsconfig.json,例如,

"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/",
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"strict": true,
"target": "es2017",
"module": "es2020",
}
# where you can set your outDir accordingly.

第二步

将当前 TS 编译器 tsc设置为监视项目根文件夹。要实现这一点,请打开另一个终端选项卡,运行以下命令并将其保留在后台。

$ tsc --watch --project ./
# tsc is your working compiler, may be different than this. I currently using global TyperScript Compiler to watch on save therefore tcs. Change to yours accordingly
# ref: https://www.typescriptlang.org/docs/handbook/compiler-options.html

这比依赖 IDE 任务监视器更简洁。

当你不再需要它的时候,简单的 Ctrl/Command + C 来终止它,甚至关闭/回收终端

  1. 在您的项目文件夹中运行 tsc —— init 来创建 tsconfig. json 文件(如果您还没有的话)

  2. 按 Ctrl + Shift + B 在 VS Code 中打开一个任务列表并选择“ tsc: watch-tsconfig.json”

  3. 完成! 您的项目将在每个保存的文件上重新编译。

这对我很有用,但是对于步骤2,我只能在任务列表中选择“ tsc: espion-tsconfig.json”(在列表中找不到“ tsc: watch-tsconfig.json”)