OpenAPI Generator生成Axios客户端后PokemonApi导出报错求助
问题描述
我使用OpenAPI Generator执行以下命令,为PokeAPI生成Axios TypeScript客户端:
npx openapi-generator-cli generate -i https://raw.githubusercontent.com/PokeAPI/pokeapi/master/openapi.yml -g typescript-axios -o ./src
生成的文件夹包含一个index.ts文件,导出所有内容:
export * from './api'; export * from './configuration';
我在自定义Turborepo包的package.json中设置main字段为该index.ts:
{ "name": "@repo/poke-client", "version": "1.0.0", "main": "./src/index.ts", "scripts": { "codegen:pokeapi": "openapi-generator-cli generate -i https://raw.githubusercontent.com/PokeAPI/pokeapi/master/openapi.yml -g typescript-axios -o ./src" }, "devDependencies": { "@openapitools/openapi-generator-cli": "^2.13.4" } }
IDE中导入提示正常,但使用tsx运行时出现错误:
backend:dev: SyntaxError: The requested module '@repo/poke-client' does not provide an export named 'PokemonApi' backend:dev: at ModuleJob._instantiate (node:internal/modules/esm/module_job:131:21) backend:dev: at async ModuleJob.run (node:internal/modules/esm/module_job:213:5) backend:dev: at async ModuleLoader.import (node:internal/modules/esm/loader:316:24) backend:dev: at async loadESM (node:internal/process/esm_loader:34:7) backend:dev: at async handleMainPromise (node:internal/modules/run_main:66:12)
我找到一个临时解决方法:
import * as pokeClient from '@repo/poke-client'; const api = new pokeClient.default.PokemonApi();
但这会导致奇怪的TypeScript和ESLint错误(代码可编译运行):
backend:lint: 2:7 error 'api' is assigned a value but never used @typescript-eslint/no-unused-vars backend:lint: 3:7 error 'POKEMONS_COUNT' is assigned a value but never used @typescript-eslint/no-unused-vars backend:lint: 13:19 error Unreachable code no-unreachable
请问如何彻底解决该问题?
解决方案
1. 修正包的导出配置(核心)
Turborepo + tsx 运行时需要明确ES模块的导出规则,仅设置main字段不足以让Node.js正确识别模块类型。需要在package.json中补充以下配置:
{ "name": "@repo/poke-client", "version": "1.0.0", "main": "./src/index.ts", "module": "./src/index.ts", // 指定ES模块入口 "type": "module", // 声明当前包为ES模块 "scripts": { "codegen:pokeapi": "openapi-generator-cli generate -i https://raw.githubusercontent.com/PokeAPI/pokeapi/master/openapi.yml -g typescript-axios -o ./src" }, "devDependencies": { "@openapitools/openapi-generator-cli": "^2.13.4" } }
2. 确保生成的代码为ES模块格式
OpenAPI Generator默认可能生成CommonJS风格的导出,需要强制生成ES6模块:
重新执行生成命令时添加额外参数:
npx openapi-generator-cli generate -i https://raw.githubusercontent.com/PokeAPI/pokeapi/master/openapi.yml -g typescript-axios -o ./src --additional-properties=module=ES6
执行后检查./src/api/index.ts,确认导出语句为ES模块格式:
export { PokemonApi, ...其他API类 };
3. 使用标准命名导入
配置完成后,即可正常使用命名导入,无需借助default:
import { PokemonApi } from '@repo/poke-client'; const api = new PokemonApi();
4. 消除ESLint/TypeScript误报
如果仍有规则误报,检查以下几点:
- 项目根目录
tsconfig.json中,compilerOptions.module需设为ESNext或ES2020及以上版本 - 确认
api变量确实在后续代码中被使用(若未使用,可删除或添加// eslint-disable-next-line @typescript-eslint/no-unused-vars临时忽略) - 排查代码逻辑,移除实际存在的不可达代码块
内容的提问来源于stack exchange,提问作者Ron Zano
相关产品推荐
相关产品推荐

