環境
- MacOS Sonoma 14.6
- Nodebrew v1
- NodeJS v22
- TypeScript v5
- Zsh
各種インストール
Nodebrew、 Node.js
# バージョン確認
$ nodebrew
$ node -v
TypeScript
$ cd /path/to/your/project
$ npm install typescript --save-dev
$ tsc -v
TypeScript を実行する
例えば下記のようにコンパイルして、
js ファイルを実行するのはちょっと手間。
$ tsc sample.ts
$ node sample.js
なので、
ts ファイルをそのまま実行できるようにする。
ts-node のインストール
最終的に ts-node ではなく tsx を使うことにしたので、
ここはスルー推奨。
# ローカル
$ cd /path/to/your/project
$ npm install ts-node --save-dev
$ node_modules/.bin/ts-node -v
もしくは
# グローバル
$ npm install -g ts-node
$ ts-node -v
ある ts ファイルを実行しようとしたら下記エラーが出た。
多分 import 関連でエラーが出たのだと思う。
$ ts-node exports.ts
TypeError: Unknown file extension ".ts" for /xxxxx/xxxxx/sample.ts
$ ts-node-esm exports.ts
(node:19561) [DEP0180] DeprecationWarning: fs.Stats constructor is deprecated.
(Use `node --trace-deprecation ...` to show where the warning was created)
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /xxxxx/xxxxx/sample.ts
$ ts-node --esm exports.ts
(node:19679) [DEP0180] DeprecationWarning: fs.Stats constructor is deprecated.
(Use `node --trace-deprecation ...` to show where the warning was created)
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /xxxxx/xxxxx/sample.ts
下記記事を参考に色々やってみたけど解決しなかったので、
違うパッケージをインストールすることにした。
tsx のインストール
$ npm install -g tsx
# バージョン確認
$ tsx -v
# 実行
$ tsx sample.ts