为何yarn tsc编译正常但node、tsc单独执行失败?
TypeScript编译与运行问题解析:yarn tsc正常、node run报错、单独tsc失败的原因
场景与代码
仅掌握Python,通过LiteLLM使用TypeScript学习OpenAI API,编写的openai.ts代码如下:
import OpenAI from 'openai'; const openai = new OpenAI({ baseURL: "http://localhost:8000", apiKey: "not-needed", }) async function main() { const chatCompletion = await openai.chat.completions.create({ messages: [{ role: 'user', content: 'what year are we in' }], model: 'gpt-3.5-turbo', }); console.log(chatCompletion.choices[0].message.content); } main();
遇到的三个异常现象
yarn tsc编译无报错- 执行
node run时提示找不到模块:
node:internal/modules/cjs/loader:1147 throw err; ^ Error: Cannot find module 'C:\Typescript\_tests_\run' at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15) at Module._load (node:internal/modules/cjs/loader:985:27) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) at node:internal/main/run_main_module:28:49 { code: 'MODULE_NOT_FOUND', requireStack: [] }
- 执行
tsc src\openai.ts时报错:
tsc src\openai.ts node_modules/openai/core.d.ts:135:5 - error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher. 135 #private; ~~~~~~~~ node_modules/openai/lib/AbstractChatCompletionRunner.d.ts:14:5 - error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher. 14 #private; ~~~~~~~~ node_modules/openai/lib/ChatCompletionStream.d.ts:13:5 - error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher. 13 #private; ~~~~~~~~ Found 3 errors in 3 files. Errors Files 1 node_modules/openai/core.d.ts:135 1 node_modules/openai/lib/AbstractChatCompletionRunner.d.ts:14 1 node_modules/openai/lib/ChatCompletionStream.d.ts:13
原因解析
1. yarn tsc正常但单独tsc src\openai.ts失败
yarn tsc执行时会自动读取项目根目录的tsconfig.json配置文件,其中应该已设置target: "ES2015"或更高版本的ECMAScript标准,该标准支持私有标识符(#private语法)。- 直接执行
tsc src\openai.ts时,TypeScript会忽略tsconfig.json,使用默认编译选项,默认target为ES3/ES5,这两个版本不支持私有标识符,因此触发报错。
2. node run提示找不到模块
- Node.js没有
run内置命令,输入node run时,Node会把run当作模块名去查找,自然找不到对应文件,因此抛出MODULE_NOT_FOUND错误。
解决办法
解决单独tsc编译报错
- 方法一:直接执行
tsc(不带文件名),让TypeScript自动读取tsconfig.json配置编译。 - 方法二:命令行手动指定编译目标版本:
tsc src/openai.ts --target ES2015
解决node运行报错
- 方法一:先通过
yarn tsc完成编译,找到编译后的JS文件(通常在dist目录下,具体看tsconfig.json的outDir配置),再运行:
node dist/openai.js
- 方法二:使用
ts-node直接运行TypeScript文件(无需提前编译):
npx ts-node src/openai.ts
内容的提问来源于stack exchange,提问作者yarun can
相关产品推荐
相关产品推荐

