ts-node TypeError [ERR_UNKNOWN_FILE_EXTENSION]:未知的文件扩展名“.ts”

mar*_*321 19 javascript node.js typescript

我正在使用,ts-node但它给了我这个错误:

$ ts-node index.ts

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts
Run Code Online (Sandbox Code Playgroud)

我尝试"type": "module"从我的中删除package.json,但在这种情况下我收到了不同的错误:

$ ts-node index.ts

(node:45) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/projects/node-hddds8/index.ts:1
import chalk from 'chalk';
^^^^^^

SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)

以下是 StackBlitz 上的复制链接:https ://stackblitz.com/edit/node-hddds8?file=index.ts

我的package.json如下所示:

{
  "name": "node-starter",
  "version": "0.0.0",
  "type": "module",
  "dependencies": {
    "chalk": "^5.0.1",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.4"
  }
}
Run Code Online (Sandbox Code Playgroud)

我的tsconfig.json看起来像这样:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "Node",
  }
}
Run Code Online (Sandbox Code Playgroud)

我的index.ts看起来像这样:

import chalk from 'chalk';

console.log(chalk.blue('Hello world!'));
Run Code Online (Sandbox Code Playgroud)

Rco*_*rNY 23

由于您正在"type": "module"使用package.jsonESM 模块,因此您需要将其添加到您的tsconfig.json

{
    "compilerOptions": {
        "module": "ESNext" // or ES2015, ES2020
    },
    "ts-node": {
        // Tell ts-node CLI to install the --loader automatically
        "esm": true
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*mek 9

ts-node-esm虽然在 tsconfig 中使用或添加ts-node 选项的解决方案esm: true适用于“较旧”的节点版本(节点 >= 20),但在ERR_UNKNOWN_FILE_EXTENSION.

解决方法是按照本问题node --loader中所述使用:

node --no-warnings=ExperimentalWarning --loader ts-node/esm file.ts
Run Code Online (Sandbox Code Playgroud)


小智 6

尝试开始你的项目ts-node-esm index.ts


use*_*882 0

可能是因为你的 typescript 中的 compilerOptions 设置为{\xe2\x80\x9cmodule\xe2\x80\x9d: \xe2\x80\x9cesnext\xe2\x80\x9d},所以它被 ts-node 解释为模块。尝试将其更改为{\xe2\x80\x9cmodule\xe2\x80\x9d: \xe2\x80\x9cCommonJS\xe2\x80\x9d}

\n