TypeScript 始め方 インストールから実行・コンパイルまで

nodejsに TypeScript を追加する必要があります。 TypeScript は基本的にコンパイルしてjsにして使用するのですが、ts-nodeをインストールすると普通のnodeのjsファイル様に実行が出来るのでデバッグが簡単です。 ここではts-nodeとコンパイルしてjsにするところまでメモしました。

インストール

typescriptとts-nodeをインストール。 フォルダは、プロジェクトのフォルダです。 以下ではyour_project_folderとしています。 グローバルでなくローカルにインストールします。 npm install は-gを付けなければ、自動的にローカルにインストールします。  your_project_folderには、フォルダー名が表示されているはずです。 私はWindowsなのでPowerShellを使っていますが、Linuxの場合はBash Shell PSが$になるだけで同じです。

Power Shell
PS your_project_folder> npm init
PS your_project_folder> npm install typescript ts-node

tsconfig.json作成

TypeScriptのコンパイラオプションファイルです。 ここでは使いませんが、一応作っておくだけです。

Power Shell
PS your_project_folder> ./node_modules/.bin/tsc --init
---------------以下は上記コマンドのメッセージ--------
Created a new tsconfig.json with:

TS 
  target: es2016
  module: commonjs
  strict: true
  esModuleInterop: true
  skipLibCheck: true
  forceConsistentCasingInFileNames: true

tsファイル作成

./test.ts
function hey(a: string): void {
    console.log("Hey, " + a + "!");
}
let b: string = "Ichiri";
hey(b);

ts-nodeで実行

Power Shell
PS your_project_folder> ./node_modules/.bin/ts-node ./test.ts
--------------
hello

./node_modules/.bin/で実行していますが、package.jsonにパスを設定すると簡単に実行できるようになります。

./package.json
  "scripts": {
    "test": "./node_modules/.bin/ts-node test.ts"
  },

npm testだけで実行できました。

Power Shell
PS your_project_folder> npm test
--------------
hello

コンパイル

ts-node同様、./node_modules/.bin/で実行しないといけず、面倒くさいので、簡単に実行できるように、package.jsonにパスを設定して実行します。

./package.json
  "scripts": {
    "test": "./node_modules/.bin/ts-node test.ts",
    "tsc": "./node_modules/.bin/tsc test.ts"
  },

npm run tscだけでコンパイルできました。

Power Shell
PS your_project_folder> npm run tsc
--------------
test.jsが出来ました。

./test.js
function hey(a) {
    console.log("Hey, " + a + "!");
}
var b = "Ichiri";
hey(b);

もっと簡単な実行は、npxを使うとrunを省略できます。

Power Shell
PS your_project_folder> npx tsc
--------------
test.jsが出来ました。

コメント

タイトルとURLをコピーしました