npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@magicbe/yapi-generator

v1.0.9

Published

yapi 生成器

Readme

@magicbe/yapi-generator

npm version License: MIT TypeScript

YAPI 接口代码生成器 - 自动生成 TypeScript/JavaScript API 代码

English | 简体中文

✨ 功能特性

  • 🚀 自动生成代码 - 根据 YAPI 接口文档自动生成 TypeScript/JavaScript 代码
  • 📝 完整类型定义 - 自动生成请求参数、响应数据的 TypeScript 类型定义
  • 🎯 智能命名 - 自动处理路径参数、连字符等特殊字符,生成规范的命名
  • 📚 JSDoc 注释 - 自动生成完整的 JSDoc 注释,包含参数说明和返回值说明
  • 🔧 灵活配置 - 支持命令行参数和交互式配置
  • 📦 零依赖运行 - 生成的代码无需额外依赖
  • 🌐 支持多种 HTTP 方法 - GET、POST、PUT、DELETE 等
  • 🎨 代码格式化 - 生成格式规范、易于阅读的代码
  • 🔄 交互式选择 - 支持交互式选择要生成的分类

📦 安装

全局安装

npm install -g @magicbe/yapi-generator
# 或
yarn global add @magicbe/yapi-generator
# 或
pnpm add -g @magicbe/yapi-generator

项目内安装

npm install --save-dev @magicbe/yapi-generator
# 或
yarn add --dev @magicbe/yapi-generator
# 或
pnpm add --save-dev @magicbe/yapi-generator

🚀 快速开始

命令行使用

# 查看版本号
gen-yapi -v

# 查看帮助信息
gen-yapi --help

# 基本使用(交互式配置)
gen-yapi

# 完整参数
gen-yapi \
  -u https://yapi.example.com \
  -t your-project-token \
  -l typescript \
  -o ./src/api \
  -c 123

# 生成所有分类
gen-yapi -u https://yapi.example.com -t your-token -a

# 生成指定分类
gen-yapi -u https://yapi.example.com -t your-token -c 123

命令行参数

| 参数 | 简写 | 说明 | 必填 | 默认值 | |------|------|------|------|--------| | --base-url | -u | YAPI Base URL | 是* | - | | --project-token | -t | Project Token | 是* | - | | --language | -l | 生成代码语言 (javascript/typescript) | 否* | typescript | | --output | -o | 输出目录 | 否* | 当前目录 | | --category | -c | 指定分类 ID 生成 | 否 | - | | --all | -a | 是否生成所有分类 | 否 | false | | --file-name-format | | 文件名格式(支持 Mustache 模板) | 否 | {{_id}} | | --version | -v | 显示版本号 | - | - | | --help | -h | 显示帮助信息 | - | - |

*注:如果未提供必填参数,将会进入交互式配置模式

文件名格式化

使用 --file-name-format 参数可以自定义生成的文件名格式,支持 Mustache 模板语法。

可用变量

项目属性 (project)

  • {{project._id}} - 项目 ID
  • {{project.name}} - 项目名称
  • {{project.basepath}} - 项目基础路径
  • {{project.uid}} - 项目创建者 ID
  • {{project.group_id}} - 分组 ID
  • {{project.project_type}} - 项目类型
  • {{project.icon}} - 项目图标
  • {{project.color}} - 项目颜色
  • {{project.add_time}} - 创建时间戳
  • {{project.up_time}} - 更新时间戳
  • 以及其他所有原始值属性(string、number、boolean)

快捷变量

  • {{_id}} - 分类 ID
  • {{name}} - 分类名称
  • {{project_id}} - 所属项目 ID
  • {{desc}} - 分类描述
  • {{uid}} - 创建者 ID
  • {{add_time}} - 创建时间戳
  • {{up_time}} - 更新时间戳

格式化示例

# 使用分类 ID(默认)
gen-yapi --file-name-format "{{id}}"

# 使用分类名称
gen-yapi --file-name-format "{{name}}"

# 使用项目 ID 和分类 ID
gen-yapi --file-name-format "yapi_{{project._id}}_{{_id}}"

# 使用项目名称和分类名称
gen-yapi --file-name-format "{{project.name}}-{{name}}"

# 使用项目基础路径和分类 ID
gen-yapi --file-name-format "api_{{project.basepath}}_{{_id}}"

# 复杂组合
gen-yapi --file-name-format "{{project.project_type}}_{{project._id}}_{{_id}}_{{name}}"

# 使用时间戳
gen-yapi --file-name-format "api_{{project._id}}_{{_id}}_{{add_time}}"

生成的文件名示例

  • {{id}}123.ts
  • {{name}}用户管理.ts
  • yapi_{{project._id}}_{{_id}}yapi_456_123.ts
  • {{project.name}}-{{name}}我的项目-用户管理.ts
  • api_{{project.basepath}}_{{_id}}api__api_v1_123.ts

注意:文件名中的非法字符(< > : " / \ | ? *)会被自动替换为下划线 _

交互式使用

如果不提供任何参数,或者缺少必填参数,工具会进入交互式配置模式:

gen-yapi

交互式配置会依次询问:

  1. YAPI Base URL
  2. Project Token
  3. 生成代码语言(JavaScript/TypeScript)
  4. 输出目录
  5. 选择要生成的分类(如果没有指定 -c-a

编程式使用

import { GeneratorYapi } from '@magicbe/yapi-generator';

// 创建生成器实例
const generator = GeneratorYapi.create({
    baseUrl: 'https://yapi.example.com',
    projectToken: 'your-project-token',
    language: 'typescript',
    output: './src/api'
});

// 加载项目信息和接口列表
await generator.loadSources();

// 生成指定分类
generator.generate(123);

// 生成多个分类
generator.generate([123, 456, 789]);

📝 生成的代码示例

TypeScript 代码示例

/** 查询参数 */
export interface GetUserListQuery {
    /** 页码 */
    page: string;
    /** 每页数量 */
    page_size: string;
}

export interface GetUserListResultDataItems {
    /** 用户ID */
    uuid?: string;
    /** 用户名 */
    name?: string;
}

/** 响应体 */
export interface GetUserListResult {
    code?: number;
    msg?: string;
    data?: GetUserListResultDataItems[];
}

/**
 * 获取用户列表
 * 
 * @see {@link https://yapi.example.com/project/123/interface/api/cat_456}
 * 
 * @param {GetUserListQuery} query 查询参数
 * @returns {Promise<GetUserListResult>} 响应体
 */
export function getUserList(query: GetUserListQuery): Promise<GetUserListResult> {
    return request.get<GetUserListResult>(`/api/v1/user/list`, { params: query });
}

路径参数示例

/**
 * 更新用户信息
 * 
 * @param {string} user_id 用户ID
 * @param {UpdateUserBody} body 请求体
 * @returns {Promise<UpdateUserResult>} 响应体
 */
export function updateUser(user_id: string, body: UpdateUserBody): Promise<UpdateUserResult> {
    return request.put<UpdateUserResult>(`/api/v1/user/${user_id}`, body);
}

🎯 代码特性

1. 完整的类型定义

  • ✅ 自动生成请求参数类型
  • ✅ 自动生成响应数据类型
  • ✅ 支持嵌套对象和数组类型
  • ✅ 正确处理可选属性

2. 规范的命名

  • ✅ 接口名称使用大驼峰命名(如 GetUserListResult
  • ✅ 函数名称使用小驼峰命名(如 getUserList
  • ✅ 自动处理路径中的特殊字符(如 -{}

3. 完整的注释

  • ✅ 接口注释
  • ✅ 属性注释
  • ✅ 函数注释(JSDoc 格式)
  • ✅ 参数说明
  • ✅ 返回值说明
  • ✅ 文档链接(@see

4. 路径参数处理

  • ✅ 自动提取路径参数(如 {user_id}
  • ✅ 参数名称规范化(如 user-iduser_id
  • ✅ 生成动态 URL(使用模板字符串)

🔧 配置选项

GeneratorYapiOptions

interface GeneratorYapiOptions {
    /** YAPI Base URL */
    baseUrl: string;
    /** Project Token */
    projectToken: string;
    /** 生成代码语言 */
    language: 'javascript' | 'typescript';
    /** 输出目录 */
    output: string;
}

📚 使用场景

场景 1:初始化项目

# 1. 全局安装
npm install -g @magicbe/yapi-generator

# 2. 交互式生成接口
gen-yapi

# 3. 在项目中使用
import { getUserList } from './api/123';

场景 2:增量更新

# 只更新指定分类
gen-yapi -u https://yapi.example.com -t your-token -c 123 -o ./src/api

场景 3:批量生成

# 生成所有分类
gen-yapi -u https://yapi.example.com -t your-token -a -o ./src/api

场景 4:自动化脚本

// scripts/generate-api.ts
import { GeneratorYapi } from '@magicbe/yapi-generator';

async function main() {
    const generator = GeneratorYapi.create({
        baseUrl: process.env.YAPI_BASE_URL!,
        projectToken: process.env.YAPI_TOKEN!,
        language: 'typescript',
        output: './src/api'
    });
    
    await generator.loadSources();
    generator.generate([123, 456, 789]);
}

main();

🛠️ 开发指南

环境要求

  • Node.js >= 16.0.0
  • TypeScript >= 5.5.0

本地开发

# 克隆项目
git clone https://github.com/magicbe/yapi-generator.git

# 安装依赖
npm install

# 构建
npm run build

# 测试
npm run test

项目结构

yapi-generator/
├── src/
│   ├── generator.ts       # 代码生成器核心
│   ├── library.ts         # CLI 入口
│   ├── index.ts           # API 导出
│   └── yapi/
│       ├── index.ts       # YAPI 客户端
│       └── type.ts        # 类型定义
├── dist/                  # 编译输出
├── package.json
├── tsconfig.json
└── README.md

🤝 贡献指南

欢迎提交 Issue 和 Pull Request!

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 创建 Pull Request

📄 许可证

本项目采用 MIT 许可证。

👤 作者

🙏 致谢

📮 联系方式

  • 主页: http://www.wangquan.top
  • GitHub: https://github.com/magicbe/yapi-generator
  • Issues: https://github.com/magicbe/yapi-generator/issues

如果这个项目对您有帮助,请给一个 ⭐️ Star!

Made with ❤️ by wang quan