LoginSignup
3
7

More than 5 years have passed since last update.

Visual StudioでTypeScriptを使ってみる

Posted at

Visual StudioでTypeScriptを使ってみます。

環境はVisual Studio 2015です。

TypeScriptのプロジェクト作成

ファイル->新規作成->プロジェクトでプロジェクト作成ダイアログを開きます。

テンプレートからTypeScriptを使用したHTMLアプリケーションを選択します。

構成

このテンプレートには画面とTypeScriptファイルとcssのみが含まれています。

constitution.PNG

app.tsでは時間を画面に表示する処理が書かれているようです。

app.ts

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor(element: HTMLElement) {
        this.element = element;
        this.element.innerHTML += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    var el = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

画面ではトランスパイルしたファイルをソースに指定します。

index.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="app.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>

    <div id="content"></div>
</body>
</html>

ビルド

ソリューションをビルドしてみます。

ビルドするとtsがjsにトランスパイルされます。

js.PNG

app.js

var Greeter = (function () {
    function Greeter(element) {
        this.element = element;
        this.element.innerHTML += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }
    Greeter.prototype.start = function () {
        var _this = this;
        this.timerToken = setInterval(function () { return _this.span.innerHTML = new Date().toUTCString(); }, 500);
    };
    Greeter.prototype.stop = function () {
        clearTimeout(this.timerToken);
    };
    return Greeter;
}());
window.onload = function () {
    var el = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};
//# sourceMappingURL=app.js.map

実行

ソリューションを実行すると下記画面が表示されます。

index.png

TypeScriptのビルド設定

ソリューションを右クリックし、プロパティを表示します。

左側にあるTypeScriptビルドを選択すると設定が表示されます。

typescript_build_setting.PNG

まとめ

Visual StudioでTypeScriptファイルを含むソリューションをビルドするとTypeScriptファイルからJavaScriptファイルにトランスパイルされます。

画面で読み込む際にはトランスパイルされたJavaScriptファイルを参照しましょう。

3
7
0

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
3
7