7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(Node18) npx ts-nodeでTypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"エラーが出る

Last updated at Posted at 2024-03-08

はじめに

tsファイルの実行につまったのでまとめます

問題

以下のコマンドを実行したところエラーが出ました

$ npx ts-node --esm ./batch/index.ts 
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/watanabejin/workspace/business_card/batch/index.ts
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
    at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
    at defaultLoad (node:internal/modules/esm/load:143:22)
    at async nextLoad (node:internal/modules/esm/hooks:750:22)
    at async nextLoad (node:internal/modules/esm/hooks:750:22)
    at async Hooks.load (node:internal/modules/esm/hooks:383:20)
    at async handleMessage (node:internal/modules/esm/worker:199:18) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

解決方法

Node.js 18.16.0では以下の方法でうまく動きました

$ npm uninstall typescript ts-node

そしてグローバルに入っていなければts-nodeをいれます

$ npm i -g ts-node

そして以下のコマンドで実行できました

$ npx node --loader ts-node/esm ./batch/index.ts

おわりに

Node20系では以下のやり方で動いたと言っていたのでそちらも真似てみてください

7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?