typescript Visual Studio Code 在保存时编译

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29996145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:38:46  来源:igfitidea点击:

Visual Studio Code compile on save

typescriptvisual-studio-code

提问by Powell Quiring

How can I configure Visual Studio Code to compile typescript files on save?

如何配置 Visual Studio Code 以在保存时编译打字稿文件?

I see it is possible to configure a task to build the file in focus using the ${file}as an argument. But I would like this to be done when a file is saved.

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

回答by zlumer

May 2018 update:

2018 年 5 月更新:

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

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

  1. Run tsc --initin your project folder to create tsconfig.jsonfile (if you don't have one already).
  2. Press Ctrl+Shift+Bto open a list of tasks in VS Code and select tsc: watch - tsconfig.json.
  3. Done! Your project is recompiled on every file save.
  1. tsc --init在您的项目文件夹中运行以创建tsconfig.json文件(如果您还没有)。
  2. Ctrl+Shift+B打开 VS Code 中的任务列表,然后选择tsc: watch - tsconfig.json
  3. 完毕!您的项目在每次保存文件时都会重新编译。

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

如果需要,您可以tsconfig.json在工作区中拥有多个文件并一次运行多个编译(例如,前端和后端分别)。

Original answer:

原答案:

You can do this with Build commands:

您可以使用 Build 命令执行此操作:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

回答by Fenton

If you want to avoid having to use CTRL+SHIFT+Band 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:

如果你想避免使用CTRL+ SHIFT+ B,而是希望出现这种情况任何时候你保存文件时,你可以在命令绑定到同一个快捷的保存操作:

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

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

这在您的 keybindings.json 中 - (使用 File -> Preferences -> Keyboard Shortcuts 前往此)。

回答by Jon Preece

If pressing Ctrl+Shift+Bseems 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.

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

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

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

tsc -w

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

而且,嘿,每次 VS Code 自动保存文件时,TSC 都会重新编译它。

This technique is mentioned in a blog post;

博客文章中提到了这种技术;

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

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

Scroll down to "Compile on save"

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

回答by bingles

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

现在 vscode 是可扩展的,可以通过扩展挂接到 on save 事件。可以在此处找到有关为 VSCode 编写扩展的良好概述:https://code.visualstudio.com/docs/extensions/overview

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

这是一个简单的例子,它只是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);
}

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

(也参考了这个 SO 问题:https: //stackoverflow.com/a/33843805/20489

Existing VSCode Extension

现有的 VSCode 扩展

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

如果您只想安装现有的扩展程序,这里是我在 VSCode 库中编写的可用扩展程序:https://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave

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

源代码可在此处获得:https: //github.com/emeraldwalk/vscode-runonsave/blob/master/src/extension.ts

回答by httpete

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.

我一直在努力争取我想要的行为。这是让 TypeScript 文件在保存时编译到我想要的配置的最简单和最好的方法,只有这个文件(保存的文件)。这是一个tasks.json 和一个keybindings.json。

enter image description here

在此处输入图片说明

回答by Dirk B?umer

Instead of building a single file and bind Ctrl+S to trigger that build I would recommend to start tsc in watch mode using the following tasks.json file:

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

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

This will once build the whole project and then rebuild the files that get saved independent of how they get saved (Ctrl+S, auto save, ...)

这将一次构建整个项目,然后重新构建独立于保存方式的文件(Ctrl+S,自动保存,...)

回答by WasiF

Updated

更新

In your tsconfig.json

在你的 tsconfig.json

"compileOnSave": true, // change to true

if problem is still there then do any of the following:

如果问题仍然存在,请执行以下任一操作:

Restart your editoror Change any route, revert it back and save the application. It'll start compiling.i.e.

重新启动编辑器更改任何路由,将其还原并保存应用程序。它会开始编译。IE

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

回答by Andzej Maciusovic

I implemented compile on save with gulp task using gulp-typescriptand incremental build. This allows to control compilation whatever you want. Notice my variable tsServerProject, in my real project I also have tsClientProject because I want to compile my client code with no module specified. As I know you can't do it with vs code.

我使用gulp-typescript和增量构建通过 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/'));

}

回答by Ignatius Andrew

Select Preferences -> Workspace Settingsand add the following code, If you have Hot reload enabled, then the changes reflect immediately in the browser

选择Preferences -> Workspace Settings并添加以下代码,如果您启用了热重载,则更改会立即反映在浏览器中

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

回答by httpete

I can say with the latest version of TypeScript 1.8.X and 1.0 of Visual Studio code, the technique I showed is obsolete. Simply use a tsconfig.json at the root level of your project and all works automatically for syntax checking. Then use tsc -w on the command line for watching / recompiling automatically. It will read the same tsconfig.json file for options and config of ts compile.

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

// tsconfig.json

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