如何自定义 NestJS CLI 的代码模板(如添加公司标准注释、特定装饰器)?

解读

国内一线/二线公司普遍要求“脚手架一键生成”的代码必须符合内部规范:统一文件头版权、作者、创建时间;强制添加 Swagger、链路追踪、权限、日志等装饰器;甚至要自动注入公司级基类。NestJS CLI 原生只提供极简模板,面试官想确认候选人是否能把“规范”落地到工程化层面,而不是每次都手工复制粘贴。回答要体现三点:① 知道 CLI 模板存在位置;② 会用官方提供的 schematics 钩子;③ 能把公司规范封装成私有 schematics 包并集成到 CI,实现“开箱即用”。

知识点

  1. NestJS CLI 底层基于 Angular DevKit Schematics,模板源文件位于 @nestjs/schematics 的 src/lib/**/files/ 目录。
  2. 自定义模板两条路线:
    a) 本地覆盖:项目根建 schematics 文件夹,用 nest generate --collection ./schematics 指向本地 collection。
    b) 私有 npm 包:把公司 schematics 发至内网 Verdaccio,通过 nest generate --collection @company/nest-schematics 全局调用。
  3. 模板语法:
    • __name@dasherize__.controller.ts 文件名变量
    • <%= classify(name) %> 类名变量
    • <% if (flat) { %>...<% } %> 条件分支
  4. 向模板注入自定义规则:在 schema.json 新增 x-prompt 字段,收集作者、需求号等信息;在 _files 里用 <%= author %> 占位。
  5. 通过 Rule 工厂函数在 factory.ts 里追加 InsertChange,可动态插入装饰器、import 语句,避免直接写死模板。
  6. 把自定义 collection 注册到 nest-cli.json:"collection": "@company/nest-schematics",实现 nest g co 默认走公司模板。
  7. 与 CI 结合:在 husky 的 pre-commit 钩子中检测“若文件头无公司版权注释则拒绝提交”,倒逼团队使用标准化模板。

答案

分四步落地公司级模板:

第一步,初始化 schematics 项目

npm init -y
npm install @angular-devkit/schematics-cli -D
schematics blank --name=nest-schematics

目录结构:

nest-schematics/
├─ src/
│  ├─ collection.json
│  ├─ controller/
│  │  ├─ index.ts
│  │  ├─ schema.json
│  │  └─ files/
│  │     └─ __name@dasherize__.controller.ts

把官方模板拷贝到 files,按需插入公司头注释:

/**
 * Copyright(C) <%= year %>  <%= author %>
 * @description <%= description %>
 * @since <%= version %>
 */

并追加公司装饰器:

@ApiTags('<%= dasherize(name) %>')
@Controller('<%= dasherize(name) %>')
@UseInterceptors(LoggingInterceptor)   // 公司日志拦截器
export class <%= classify(name) %>Controller {}

第二步,声明 schema.json 收集额外信息

{
  "$schema": "http://json-schema.org/schema",
  "id": "nest-controller",
  "type": "object",
  "properties": {
    "author": {
      "type": "string",
      "x-prompt": "请输入作者工号"
    }
  }
}

在 factory.ts 里把 options.author 注入模板变量。

第三步,打包并发布到内网仓库

npm run build
npm publish --registry http://verdaccio.company.com

第四步,在业务项目一键使用

nest new demo --collection @company/nest-schematics
nest g co user --collection @company/nest-schematics

生成的文件已自带版权注释、Swagger 标签与公司拦截器,无需手工改动。

拓展思考

  1. 多团队共存:若 A 团队用 REST、B 团队用 GraphQL,可在 collection 里加 style 参数,同一条 nest g res 命令根据选择生成不同模板,避免维护两套脚手架。
  2. 版本漂移治理:把 schematics 包纳入公司制品库快照策略,每次升级发正式版前跑自动化测试,确保模板语法与最新 NestJS 版本兼容。
  3. 反向校验:在模板里预埋 // <auto-generated> 标识,配合 eslint-plugin-header 做提交检查,防止开发者把生成的文件手动改到“脱离规范”。
  4. 与 Monorepo 结合:在 Nx 工作区里把 @company/nest-schematics 作为 workspace-generator,实现“一个命令生成模块 + 接口文档 + 单元测试 + Dockerfile”,把研发路径压缩到 5 分钟以内,真正达到企业级“可复制”的交付标准。