LoginSignup
25
24

More than 5 years have passed since last update.

Typescript を使う為の環境構築めも

Last updated at Posted at 2014-04-27

目的

業務で Coffeescript を書いています.
今回は, 別の AltJS である Typescript を知ること, その為に Typescript を使う準備をするのを目標にやったことのメモです.

Typescript ではろーわーるど:D

インストールしてはろーわーるどしてみる

グローバルでなく作業ディレクトリのみにインストールします.

$ npm i typescript
$ ./node_modules/.bin/tsc -v
Version 1.0.0.0
$ emacs hello.ts
$ cat hello.ts
console.info('hello:D');
$ ./node_modules/.bin/tsc hello.ts
$ node hello.js
hello:D

簡単な構文を書いてみる

Typescript

hello.ts
module Greeting {
    export class Hello {
        constructor(private text : string) {
        }
        say() : void {
            console.log(this.text);
        }
    }
}

var hello : Greeting.Hello = new Greeting.Hello("Hello, World!");
hello.say();

コンパイル後...

Javacript

hello.js
var Greeting;
(function (Greeting) {
    var Hello = (function () {
        function Hello(text) {
            this.text = text;
        }
        Hello.prototype.say = function () {
            console.log(this.text);
        };
        return Hello;
    })();
    Greeting.Hello = Hello;
})(Greeting || (Greeting = {}));

var hello = new Greeting.Hello("Hello, World!");
hello.say();

ふむふむ... Coffeescript と違って型型な構文(・.・)

Gulp でテンプレートを作った

ts ファイルを監視してコンパイルさせる html テンプレートを作っておきました.
なんとなく Grunt でなく Gulp を使ってみました.

フォルダ構成

$ tree . -L 3
.
|-- dist
|   |-- css
|   |   `-- hello.css
|   |-- index.html
|   `-- js
|       `-- all.min.js
|-- gulpfile.js
|-- package.json
`-- src
    |-- css
    |   `-- hello.styl
    |-- index.jade
    `-- js
        `-- hello.ts

コンパイルされた Javascript ファイルは index.html で読み込んでいます.

gulp の設定ファイルの書き方は Coffeescript と同じ

gulpfile.js
var ts = require('gulp-tsc');

gulp.task('ts', function() {
  gulp.src(['./src/js/*.ts'])  // Typescript ファイルのパス
    .pipe(ts())  // コンパイルする
    .pipe(uglify())  // minify する
    .pipe(concat('./all.min.js'))  // 1つのファイルにまとめる
    .pipe(gulp.dest('./dist/js/'));  // コンパイル後のファイルのパス
});

Grunt でも同様に書けそうです.

使い方

$ mkdir HOGE
$ cd HOGE
$ git clone git@github.com:naoiwata/typescript-project.git .
$ npm install
$ ./node_modules/.bin/gulp

ブラウザで http://localhost:8888 を開いて開発. livereload が発動しているのでファイル更新を監視して自動でコンパイルしてくれます.

結果 & 次回

環境構築は Coffeescript と同じように出来ました. 次回は Typescript の構文を見ながらその違いを調査してみます. 型のある Javascript にわくわくしています:D

Refferences

http://www.typescriptlang.org/Tutorial
https://www.npmjs.org/package/typescript
https://www.npmjs.org/package/gulp-tsc

25
24
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
25
24