LoginSignup
60
67

More than 5 years have passed since last update.

Visual Studio CodeでTypeScriptをコンパイルする

Last updated at Posted at 2015-05-26

Visual Studio CodeはMicrosoftが作っているだけあって、TypeScriptの補完がいい感じなのですが、
VS Code上で.tsファイルをコンパイル(トランスパイル)する方法がわからなかったので、調べてみました。

ここに書いてありました。
https://code.visualstudio.com/docs/tasks

予めtscがインストールされている必要があります。

※以下はVisual Studio Code 0.7.0 で確認しています。

設定方法

VS Codeでプロジェクトを開いた状態で、Ctrl + Shift + P (MacはCommand + Shift + P)を押して
コマンドパレットを開き、"Task"とかを入力し、「Tasks: Configure Task Runner」を検索、選択します。
※プロジェクトを開いた状態(「EXPLORE」が表示されている状態)でないと、Tasks〜は表示されません。

すると、以下のようなtasks.jsonというファイルが生成されます。

tasks.json
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process

// A task runner that calls the Typescript compiler (tsc) and
// Compiles a HelloWorld.ts program
{
    "version": "0.1.0",

    // The command is tsc. Assumes that tsc has been installed using npm install -g typescript
    "command": "tsc",

    // The command is a shell script
    "isShellCommand": true,

    // Show the output window only if unrecognized errors occur.
    "showOutput": "silent",

    // args is the HelloWorld program to compile.
    "args": ["HelloWorld.ts"],

    // use the standard tsc problem matcher to find compile problems
    // in the output.
    "problemMatcher": "$tsc"
}

(以下省略)

これがそのままTypeScriptをコンパイルするタスクの設定となるようです。
argsがコンパイル対象のファイルなので、ここに.tsファイルを列挙していきます。

npmでtscをインストールしている場合で、このままでエラーになる場合は、
"isShellCommand": trueを追記し、tsc.exetscにすればOKでした。

(0.1.0で確認した際はMacでもWindows用のTaskが自動生成されていたっぽいですが、最新版では修正不要でした)

これでCtrl + Shift + Bを押すと、.tsファイルがコンパイルされ、.jsファイルが生成されます。
左下でクルクル回っているのがコンパイル中の表示で、それが消えるとコンパイル完了です。

おわりに

Tasksは他にも色々できそうな感じなので、使いこなすと便利そう。

できればatom-typescriptみたいに、.tsファイルを保存した時に、
自動でコンパイルしてくれるといいんだけど。。。できるのかな?

(コメントで情報をいただきました)

.tsファイルを保存した際に自動でコンパイルを実行するには、いくつか方法があるようですが、
一番簡単な方法は"args"に"-w"(または"--watch")オプションをつけてしまうことです。
つまりtsc -wで実行するということですね。

tasks.json
    // args is the HelloWorld program to compile.
    "args": ["-w", "HelloWorld.ts"],

この状態で一度Ctrl + Shift + Bを実行すると、watchオプション付きでtscが実行されるため、
それ以降は指定ファイルを保存した際に自動でコンパイルされます。

この方法の場合、Taskが実行されたままの状態となりますが、もしTaskを停止したい場合は
コマンドパレットから「Tasks: Terminate Running Task」を実行することで停止できる。。。
はずですが、時々停止できないことがあるようです。。。

以上

60
67
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
60
67