使用openapi-typescript-codegen生成类型时遇“fetch is not defined”错误求助
解决openapi-typescript-codegen的"fetch is not defined"错误并重新生成类型
1. 检查Node.js版本
fetch 从Node.js 18开始才内置到全局环境,版本低于18会触发该错误。先确认当前版本:
node -v
- 版本≥18:跳过下一步,直接检查后续配置
- 版本<18:要么升级Node.js到18+,要么添加fetch polyfill
2. 添加fetch polyfill(Node.js <18适用)
不要单独安装fetch包(依赖问题多),改用成熟的cross-fetch:
# 安装cross-fetch作为开发依赖 npm install cross-fetch --save-dev # 或使用yarn yarn add cross-fetch --dev
在生成命令中指定使用该polyfill:
openapi-typescript-codegen --input http://你的SpringBoot-Swagger地址 --output ./指定输出目录 --fetch cross-fetch
如果是在package.json的scripts中配置,修改为:
{ "scripts": { "generate-api-types": "openapi-typescript-codegen --input http://你的Swagger端点 --output ./src/api/types --fetch cross-fetch" } }
3. 适配Node环境配置
添加--platform node参数,让工具自动适配Node环境的fetch逻辑:
openapi-typescript-codegen --input http://你的Swagger地址 --output ./指定输出目录 --platform node
4. 清理依赖缓存重新安装
若更新后依赖缓存混乱,导致polyfill无法加载,执行以下步骤:
# 删除旧依赖和锁文件 rm -rf node_modules package-lock.json yarn.lock # 重新安装依赖 npm install # 或yarn install
之后再运行生成命令。
5. 手动指定fetch路径(兜底方案)
如果上述方法无效,直接指定polyfill的具体路径:
openapi-typescript-codegen --input http://你的Swagger地址 --output ./指定输出目录 --fetch ./node_modules/cross-fetch/dist/node-ponyfill.js
内容的提问来源于stack exchange,提问作者MBD
相关产品推荐
相关产品推荐

