首页 文章

visual studio代码编译保存

提问于
浏览
118

如何配置visual studio代码以在保存时编译打字稿文件?我看到可以使用 ${file} 作为参数来配置任务以构建焦点文件 . 但我希望在保存文件时完成此操作 .

11 回答

  • 5

    2018年5月更新:

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

    • 在项目文件夹中运行 tsc --init 以创建 tsconfig.json 文件(如果您还没有) .

    • 按Ctrl Shift B在VS Code中打开任务列表,然后选择 tsc: watch - tsconfig.json .

    • 完成!每个文件保存都会重新编译您的项目 .

    如果需要,您可以在工作区中包含多个 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

  • 1

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

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

    这包含在你的keybindings.json中 - (使用文件 - >首选项 - >键盘快捷键转到此处) .

  • 6

    如果按Ctrl Shift B似乎需要付出很多努力,您可以打开"Auto Save"(文件>自动保存)并使用NodeJS观察项目中的所有文件,并自动运行TSC .

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

    tsc -w
    

    并且嘿presto,每次VS Code自动保存文件,TSC将重新编译它 .

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

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

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

  • 17

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

    enter image description here

  • 2

    Write an Extension

    现在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

    Existing VSCode Extension

    如果您只想安装现有的扩展程序,可以在VSCode库中找到以下内容:https://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave

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

  • 145

    而不是构建单个文件并绑定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,自动保存,...)

  • 4

    我使用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/'));
    
    }
    
  • 1

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

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

    我可以说最新版本的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" ]
    }
    
  • 31

    你可能在 tsconfig.json

    "compileOnSave": false, // turn it to true and save
    

    如果问题仍然存在,则更改任何路由并将其还原并保存应用程序 . 它会开始编译,即

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

    如果这没有解决你的问题,那么尝试其他好的答案

相关问题