1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

最小構成でTypeScriptを動かす(console.logを出す)手軽で最短な方法

1
Posted at

細かいことはさておき

nvmとかtsconfig.jsonとかさておき。

console.logを動かしたい

これを実行させたい。

console.log("TypeScript動きました");

前提

TypeScriptはJavaScriptにコンパイルしてから動かします。

Node.jsは要ります

JavaScriptをローカル実行させたいので要ります。

WindowsならNode.jsのexeをダウンロードしてインストール。
Linuxならyum install nodejs npmなどでインストール。

TypeScriptは要ります

TypeScriptなので要ります。

好きなディレクトリを切って、
その場所でnpm install typescriptでインストール。

TypeScriptのコンパイラの場所

グローバルインストールしなければ
上記コマンドを打ったときにできるnode_modulesの中にインストールされます。
コンパイラの本体はnode_modules/.bin/tscです。

TypeScriptのファイルを作る

index.tsみたいな名前のファイルを作って、こんな感じで書き込みます。

console.log("TypeScript動きました");

TypeScriptをコンパイルしてJavaScriptにします

./node_modules/.bin/tsc index.ts

これで
index.tsと同じ場所にindex.jsというファイルが出来ます。

コンパイルされたJavaScriptを実行します

node index.js

そしたら
TypeScript動きました
と出ます。

最後に

npm install typescriptでインストールしたときに勝手に出来る
package.jsonというファイルの中はこんな風になりますが、

{
  "dependencies": {
    "tsc": "^2.0.4",
    "typescript": "^6.0.3"
  }
}

ここにscriptsというのを以下のように3行足してあげると、

{
  "scripts": {
    "debug": "tsc index.ts && node index.js"
  },
  "dependencies": {
    "tsc": "^2.0.4",
    "typescript": "^6.0.3"
  }
}

npm run debugと打つだけでコンパイルと実行を同時にしてくれるようになります。

index.tsの中身を

console.log("TypeScript変更しました");

に修正してからnpm run debugと打つと
TypeScript変更しました
と出ます。

おしまい。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?