node.js」カテゴリーアーカイブ

node.js + TypeScript でいまどきにふさわしいHelloWorldを

わけあってnode.jsどっぷりな世界に浸からねばならなそう。
とはいえ、素のJavaScriptなど書きたくもない。
せめてECMAScript6は使わせて… おっさんでもクラスくらいは使いたい…
で、ちょっといじってみたけど、やっぱりまだまだねnode.jsのES6対応。
つーことで、MS様のお力を借りて快適にnode.js生活をおくるためにTypeScriptに手を出すことにしたんだ。

まずはhello worldだよね。
せっかくのTypeScriptだし、ムダにモダンに書いてみようとした結果がこちら。

class HelloWorld {
    constructor(message:string) {
        this._message = message;
    }

    private _message:string;

    say():void {
        console.log(this._message);
    }
}

const hello_world = new HelloWorld("こんにちは世界");
hello_world.say();

実にムダにTypeScriptの機能を使いまくってみました感アリアリのhello world。
さて、node.jsくんはこれを実行できるかな?

まずはES5相当でコンパイルして実行。

C:\hogehoge>tsc -t ES5 helloworld.ts

C:\hogehoge>node helloworld.js
こんにちは世界

まあ妥当。

次はみんなお待ちかねのES6だ。

C:\hogehoge>tsc -t ES6 helloworld.ts

C:\hogehoge>node helloworld.js
C:\hogehoge\helloworld.js:1
(function (exports, require, module, __filename, __dirname) { class HelloWorld {

                                                              ^^^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:140:18)
    at node.js:1001:3

残念無念。
まだnode.jsくんにはES6は早過ぎたようだ。
とも思ったが、”use strict”を書いてないからじゃね? と気付いて、最初の行に追加してコンパイル。

C:\hogehoge>tsc -t ES6 helloworld.ts

C:\hogehoge>node helloworld.js
こんにちは世界

よかったよかった。
でもまだいるのか謎の呪文”use strict”…