如何配置Visual Studio代码以在保存时编译打字稿文件?
我看到可以使用${file}
作为参数来配置任务以构建焦点文件。但我希望在保存文件时完成此操作。
截至2018年5月,您不再需要手动创建tsconfig.json
或配置任务运行器。
tsc --init
以创建tsconfig.json
文件(如果您还没有)。tsc: watch - tsconfig.json
。您可以在工作区中包含多个tsconfig.json
文件,并在需要时一次运行多个编译(例如,分别为前端和后端)。
您可以使用Build命令执行此操作:
使用tsconfig.json
创建一个简单的"watch": true
(这将指示编译器观察所有编译的文件):
{
"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
我可以说最新版本的TypeScript 1.8.X和1.0的Visual Studio代码,我展示的技术已经过时了。只需在项目的根级别使用tsconfig.json,它们都会自动进行语法检查。然后在命令行上使用tsc -w自动观看/重新编译。它将读取相同的tsconfig.json文件以获取ts compile的选项和配置。
// tsconfig.json
{
"compilerOptions": {
"module": "amd",
"target": "ES5",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"inlineSourceMap": true
},
"exclude": [ "node_modules" ]
}
尝试了上面的方法,但是当它感觉到它时,我停止了自动编译,因为要观察的最大文件已超过限制。
运行cat /proc/sys/fs/inotify/max_user_watches
命令。
如果它显示的文件数量较少,包括node_modules,则以root权限打开文件/etc/sysctl.conf
并追加
fs.inotify.max_user_watches=524288
进入文件并保存
再次运行cat命令以查看结果。它会工作!希望!
更新
在你的tsconfig.json
"compileOnSave": true, // change to true
如果问题仍然存在,则更改任何路由并将其还原并保存应用程序。它会开始编译,即
const routes: Routes = [
{
path: '', // i.e. remove , (comma) and then insert and save, it'll compile
component: VersionsComponent
}
]
我希望这会对某人有所帮助。虽然这不是永久的解决方案,但它会有效,直到您获得更好的解决方案。
在保存时自动编译的一种非常简单的方法是在终端中键入以下内容:
tsc main --watch
其中main.ts
是您的文件名。
请注意,这只会在此终端打开时运行,但这是一个非常简单的解决方案,可以在您编辑程序时运行。
如果你想避免使用CTRL
+ SHIFT
+ B
,而是希望在你保存文件时发生这种情况,你可以将命令绑定到与保存操作相同的快捷方式:
[
{
"key": "ctrl+s",
"command": "workbench.action.tasks.build"
}
]
这包含在你的keybindings.json中 - (使用文件 - >首选项 - >键盘快捷键转到此处)。
如果按Ctrl + Shift + B似乎需要付出很多努力,您可以打开“自动保存”(文件>自动保存)并使用NodeJS观察项目中的所有文件,并自动运行TSC。
打开Node.JS命令提示符,将目录更改为项目根文件夹并键入以下内容;
tsc -w
并且嘿presto,每次VS Code自动保存文件,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);
}
(也在这个SO问题上引用:https://stackoverflow.com/a/33843805/20489)
现有的VSCode扩展
如果你只想安装一个现有的扩展,这是我在VSCode库中提供的那个:https://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave
源代码可在此处获取:https://github.com/emeraldwalk/vscode-runonsave/blob/master/src/extension.ts
而不是构建单个文件并绑定Ctrl + S来触发该构建,我建议使用以下tasks.json文件在监视模式下启动tsc:
{
"version": "0.1.0",
"command": "tsc",
"isShellCommand": true,
"args": ["-w", "-p", "."],
"showOutput": "silent",
"isWatching": true,
"problemMatcher": "$tsc-watch"
}
这将构建整个项目,然后重建保存的文件,而不管它们如何保存(Ctrl + S,自动保存,...)
我使用gulp-typescript和incremental build实现了使用gulp任务保存的编译。这允许控制任何你想要的编译。注意我的变量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/'));
}
选择首选项 - >工作区设置并添加以下代码,如果启用了热重新加载,则更改会立即反映在浏览器中
{
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/*.js.map": true,
"**/*.js": {"when": "$(basename).ts"}
},
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000
}