32
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ts-node の Unknown file extension ".ts" エラーを解決する

Last updated at Posted at 2023-01-25

概要

ts-node で TypeScript のコードを実行しようとしたとき以下のようなエラーが出ることがある。

npx ts-node src/index.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /Users/hoge/workspace/fuga/src/index.ts

調べてみると、解決策の1つとして package.json から "type": "module" を消せ、というのが挙げられていることがあるが、これは消したくない。
どうしたら良いか。

解決策 1

そもそも、最近では ts-node ではなく tsx を使うほうが主流らしい。

npx tsx src/index.ts

解決策 2

ts-node を使いたい場合は --esm オプションをつけて実行する手段がある。

npx ts-node --esm src/index.ts

解決策 3

ts-node を使いたい場合は tsconfig.json に以下の記述を追加する手段もある。

tsconfig.json
{
  // other settings...
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  }
}

解決策 4

ts-node ではなく node で --loader ts-node/esm を指定する方法もある。

node --loader ts-node/esm src/index.ts
32
12
2

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
32
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?