JavaScriptプログラムに関する各種メモ書き

ts-node より高速な tsx による typescript ファイルの実行

● ( tsx ) 準備

npm i -D tsx

● ( tsx ) 実行

npx tsx <typescriptファイル名>

以上です。

 

ts-node を使いたい場合はこちら。

● ( ts-node ) 準備

npm install --save ts-node

● ( ts-node ) プロジェクトの初期化も行う場合

npx tsc --init --target es2015

tsconfig.json

"module": "esnext",

  ↓

"module": "commonjs",

● ( ts-node ) 実行

npx ts-node <実行したいtypescriptファイル名>

● ( ts-node ) 既存の tsconfig.json を変更せずに実行したい

そのまま実行すると以下のようなエラーとなることがあります

(node:42851) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

その場合は実行用の tsconfig.json を作成してその設定ファイルを明示的に指定しながら実行します。

tsconfig.cli.json

{
  "compilerOptions": {
    // ts-node対応 esnext → NodeNext
    "module": "NodeNext",
  }

  // ts-node
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  }
}

--project <設定ファイル名> を加えて実行します。

npx ts-node --project tsconfig.cli.json src/sample.ts
No.2191
01/31 09:53

edit