typescript 设置 Visual Studio Code 以在构建和调试时转换打字稿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39679237/
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-10-21 03:52:30  来源:igfitidea点击:

Setup Visual Studio Code to transpile typescript on build and debug

typescriptvisual-studio-code

提问by user3147973

I'm a long time (15+ years) Visual Studio user and am excited to learn both Typescript and the new leaner, meaner Visual Studio Code. I've been trying to setup VSCode like VS, where when you hit F5 it transpiles to Javascript and launches the debugger.

我是一个很长一段时间(15 年以上)的 Visual Studio 用户,很高兴学习 Typescript 和新的更精简、更简洁的 Visual Studio Code。我一直在尝试像 VS 一样设置 VSCode,当您按 F5 时,它会转换为 Javascript 并启动调试器。

I've found posts that trigger it on save, or using another shortcut (run via tasks.json) - but I'm really surprised there isn't a way of doing this on such a fundamental command, unless I'm really missing something embarrassingly obvious.

我发现在保存或使用其他快捷方式(通过 tasks.json 运行)时触发它的帖子 - 但我真的很惊讶在这样一个基本命令上没有办法做到这一点,除非我真的很想念令人尴尬的显而易见的事情。

At this point I'm just trying to use the "Hello World" greeter samplechecked out directly from Microsoft, where it has a manual step of tsc --sourcemap greeter.ts. I just want that to happen automatically, like it does in VS, on any files that need transpiling before I start to run / debug.

在这一点上,我只是尝试使用直接从 Microsoft 检出的“Hello World”欢迎程序示例,其中手动步骤为tsc --sourcemap greeter.ts. 我只是希望在开始运行/调试之前,在任何需要转译的文件上,像在 VS 中一样,自动发生这种情况。

Does anyone know how to do this? Thank you.

有谁知道如何做到这一点?谢谢你。

回答by user3147973

So, using help from responses here was the path of least resistance. After opening vscode, I:

因此,在这里使用响应的帮助是阻力最小的路径。打开vscode后,我:

  1. File -> Open Folder
  2. Created an empty sub-folder within my code directory called HelloWorld in this case
  3. Created a tsconfig.jsonfile and copied the example from this articlewhich is:
    {
        "compilerOptions": {
            "target": "es5",
            "module": "commonjs",
            "sourceMap": true
        }
    }
  4. Created a helloWorld.tsas directed by the same article, which is:
    class Startup {
    public static main(): number {
        console.log('Hello World');
        return 0;
        }
    }
    Startup.main();
  5. Hit F5 (to Debug) and VSCode asked me if I wanted a Node.js environment or a VSCode environment, I selected Node.js.
  6. It generated me a launch.json, where I did the following edits:
  7. Switched "program": "${workspaceRoot}/app.js",to "program": "${workspaceRoot}/helloWorld.js",
  8. Replaced the null in preLaunchTask to: "preLaunchTask": "tsc",
  9. Replaced the 3 instances of sourceMapsfrom false to true.
  10. Hit F5 again, VSCode pops up an info saying no task runner configured. I click configure and select TypeScript - Watch Mode.
  11. Put a breakpoint on a line in my ts file
  12. Hit F5 one last time and everything works!
  1. 文件 -> 打开文件夹
  2. 在这种情况下,在我的代码目录中创建了一个名为 HelloWorld 的空子文件夹
  3. 创建了一个tsconfig.json文件并复制了本文中的示例,即:
    {
        "compilerOptions": {
            "target": "es5",
            "module": "commonjs",
            "sourceMap": true
        }
    }
  4. 按照同一篇文章的指示创建了一个helloWorld.ts,它是:
    class Startup {
    public static main(): number {
        console.log('Hello World');
        return 0;
        }
    }
    Startup.main();
  5. 按 F5(调试),VSCode 问我想要 Node.js 环境还是 VSCode 环境,我选择了Node.js
  6. 它为我生成了一个launch.json,我在其中进行了以下编辑:
  7. 交换“程序”: “$ {} workspaceRoot /app.js”,“程序”: “$ {} workspaceRoot / helloWorld.js
  8. 将 preLaunchTask 中的 null 替换为:“preLaunchTask”:“ tsc”,
  9. sourceMaps的 3 个实例从 false替换为true
  10. 再次按 F5,VSCode 会弹出一条信息,说没有配置任务运行器。我单击配置并选择TypeScript-Watch Mode
  11. 在我的 ts 文件中的一行上放置一个断点
  12. 最后一次按 F5,一切正常!

So tsc compiler seems pretty slow, takes about 4-5 seconds to transpile on my 2 year old Win10 computer. I see the benefit of TypeScript - Watch Mode so it could it's transpiling as you hit Save. Otherwise, if you transpile everytime before you debug, it doesn't seem to detect whether it needs a transpile or not, so this is the ideal scenario that matches what Visual Studio developers are used to.

所以 tsc 编译器看起来很慢,在我 2 岁的 Win10 计算机上编译需要大约 4-5 秒。我看到了 TypeScript - Watch Mode 的好处,因此它可以在您点击 Save 时进行转换。否则,如果每次在调试之前都进行转译,它似乎不会检测是否需要转译,因此这是与 Visual Studio 开发人员习惯的理想场景相匹配。

回答by Jesse Johnson

Essentially VS Code allows you to create tasks to automate development processes (cleaning files/folders, compiling, bundling, etc.) and also allows you to create environment configurations to run your project.

本质上,VS Code 允许您创建任务以自动化开发过程(清理文件/文件夹、编译、捆绑等),还允许您创建环境配置来运行您的项目。

To have them work together the environment configuration allows specification of a preLaunchTaskwhich will run the defined task before debugging. To create a workflow similar to Visual Studio you could create a compile task and run the task before the debugger by setting it as the preLaunchTask.

为了让它们一起工作,环境配置允许指定一个preLaunchTask,它将在调试之前运行定义的任务。要创建类似于 Visual Studio 的工作流,您可以创建一个编译任务并通过将其设置为preLaunchTask在调试器之前运行该任务。

Example running tsc(TypeScript compiler) before debugging

调试前运行tsc(TypeScript 编译器)的示例

1.Create a tsconfig.jsonfile in the root of your project with your choice of compile options.

1.使用您选择的编译选项在项目的根目录中创建一个tsconfig.json文件。

Example tsconfig.jsonfile (You may need to change the modulesetting to best suit your project. amdis typically a web project, commonjsis typically a node.jsproject but everyone's preference varies:

例如tsconfig.json文件(您可能需要更改模块的设置,以最适合您的项目。AMD是典型的web项目,CommonJS的通常是一个Node.js的项目,但每个人的喜好不同而不同:

{
    "compilerOptions": {
        "target": "es6",
        "module": "amd",
        "sourceMap": true,
        "allowSyntheticDefaultImports": true
    },
    "exclude": [
        "node_modules",
        "bower_components",
        "jspm_packages",
        "tmp",
        "temp"
    ]
}

2.Create a launch.jsonfile to run and debug your projectand set the preLaunchTaskto tsc.

2.创建一个launch.json文件来运行和调试您的项目,并将preLaunchTask设置为tsc

The easiest way to do this is simply hit F5. The first time you run it will ask to "Select an environment", if you have already created a launch.json file and would like to start fresh, delete the file. For TypeScript I normally choose node.jswhich will allow you to run in process or within a web context with frameworks such as express.

最简单的方法就是点击F5。第一次运行时,它会询问“选择一个环境”,如果您已经创建了一个 launch.json 文件并想重新开始,请删除该文件。对于 TypeScript,我通常选择node.js,它允许您在进程中或在 web 上下文中使用express等框架运行。

Example launch.jsonfile (this example is of an expressapp):

示例launch.json文件(这个示例是一个express应用程序):

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/bin/www",
            "stopOnEntry": false,
            "args": [],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": "tsc",
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "console": "internalConsole",
            "sourceMaps": false,
            "outDir": null
        }
    ]
}

回答by Burt_Harris

The short answer (in a new project directory) is:

简短的回答(在一个新的项目目录中)是:

  • Press Ctrl+Shift+Bto Build your project in VSCode
  • If .vscode/tasks.jsonis not already configured, a message will give you the option to Configure Task Runner, press that button.
  • Choose one of the two predefined TypeScript options.
  • You can close the tasks.jsonwindow this opened up.
  • Ctrl+Shift+B在 VSCode 中构建您的项目
  • 如果.vscode/tasks.json尚未配置,则会有一条消息为您提供配置任务运行器的选项,请按该按钮。
  • 选择两个预定义的 TypeScript 选项之一。
  • 你可以关闭tasks.json这个打开的窗口。

After having tried both TypeScript options, I prefer the ... in watch modeoption. That way, after starting the background process with Ctrl+Shift+Bonce, incremental transpiles happen whenever a file is saved, making launching the program for debugging that much faster...

在尝试了两种 TypeScript 选项后,我更喜欢... in watch 模式选项。这样,在使用Ctrl+Shift+B启动后台进程一次后,每次保存文件时都会发生增量转换,从而更快地启动调试程序......

For more details, follow this link: http://code.visualstudio.com/docs/languages/typescript#_transpiling-typescript-into-javascript

有关更多详细信息,请访问此链接:http: //code.visualstudio.com/docs/languages/typescript#_transpiling-typescript-into-javascript

If you want to generate a source map (a good idea), you need to setup tsconfig.json. The quick way to do that from VSCode is:

如果你想生成一个源映射(一个好主意),你需要设置tsconfig.json. 从 VSCode 执行此操作的快速方法是:

  • Press Ctrl+Shift+Cto open up a command line window.
  • type the command tsc --init --sourceMapto set up a template tsconfig.json
  • type the command exit
  • Ctrl+Shift+C打开命令行窗口。
  • 键入命令tsc --init --sourceMap以设置模板tsconfig.json
  • 输入命令 exit

Finally, if you want to usethe source map while debugging, you need to generate and edit the .vscode/launch.jsonfile. The quick way to do that is:

最后,如果要在调试时使用源映射,则需要生成和编辑.vscode/launch.json文件。快速的方法是:

  • If .vscode/launch.jsondoesn't already exist, pressing F5will prompt you to choose and environment. Choose Node.js.
  • Edit the generated file replacing all occurances of "sourceMaps": falsewith "sourceMaps": true.
  • 如果.vscode/launch.json不存在,按F5将提示您选择和环境。选择Node.js
  • 编辑生成的文件,替换所有出现的"sourceMaps": falsewith "sourceMaps": true

I'm not sure why the defaults omit source maps, it currently seems like one of the most common bumps in the road for people starting to use VSCode + TypeScript.

我不确定为什么默认值会忽略源映射,对于开始使用 VSCode + TypeScript 的人们来说,它目前似乎是道路上最常见的颠簸之一。