TS-node-ESM 抛出"SyntaxError: Unexpected identifier",没有任何错误跟踪



我想运行一个使用ES模块导入的TS文件(例如import fs from "fs"(。我已经完成了以下步骤:

  1. 将文件从myScript.ts重命名为myScript.mts
  2. 通过npm全局安装了最新版本的ts-node,并在package.json中创建了npm脚本"custom-script": "ts-node-esm ./myScript.mts"
  3. 使用以下tsconfig文件
{
"compilerOptions": {
"target": "ES2018",
"module": "ESNext",
"moduleResolution": "Node",
"lib": ["ESNext", "ESNext.AsyncIterable", "DOM"],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"baseUrl": ".",
"noErrorTruncation": true,
"resolveJsonModule": true,
"types": ["@types/node"]
},
"exclude": ["node_modules"]
}
  1. 运行npm run custom-script

现在我得到以下控制台输出:

> ts-node-esm ./myScript.mts
SyntaxError: Unexpected identifier
at Loader.moduleStrategy (internal/modules/esm/translators.js:141:18)
at async link (internal/modules/esm/module_job.js:42:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! myproject@1.0.0 custom-script: `ts-node-esm ./myScript.mts`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the myproject@1.0.0 custom-script script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersmeAppDataRoamingnpm-cache_logs2022-10-02T19_08_42_558Z-debug.log 

就是这样,没有有用的堆栈跟踪。没有错误来源的行。甚至无法打开它在跟踪中显示的文件,因为它们是内部文件,VSC找不到它们。

为什么会发生这种情况,我该如何解决?

我找到了错误的来源。我在脚本文件中使用了一个导入断言,如下所示:

import CONFIG from "./config.json" assert { type: "json" }

这只适用于新版本的nodejs,而我使用的是旧版本。

但我仍然不明白的是,为什么ts节点没有在错误堆栈跟踪中显示这一行。

相关内容

最新更新