React+TypeScript与Nest.js跨仓库共享TypeScript类型方案咨询
独立仓库下前后端TypeScript类型共享方案
方案1:Git子模块同步类型目录
- 把后端的TypeScript类型(比如实体、DTO定义)单独抽成一个独立Git仓库,然后将这个仓库作为子模块引入前端项目的指定目录(如
src/shared-types)。 - 后端更新类型后直接提交到类型仓库,前端只需拉取子模块的最新代码即可,无需维护版本号,完全同步后端最新类型。
- 核心操作:
- 后端将类型目录推为独立仓库:
cd backend/src/types && git init && git remote add origin <类型仓库地址> && git push - 前端添加子模块:
git submodule add <类型仓库地址> src/shared-types - 前端更新类型:
git submodule update --remote
- 后端将类型目录推为独立仓库:
- 优势:类型完全与后端源码一致,避免Swagger的类型偏差;无需版本管理,从根源杜绝版本不一致问题。
方案2:CI/CD自动推送编译后的类型文件
- 在后端项目中配置脚本,用
tsc单独编译类型文件生成.d.ts声明文件,然后通过CI/CD(如GitHub Actions、GitLab CI)将编译后的文件推送到前端仓库的指定目录。 - GitHub Actions示例片段:
jobs: sync-types: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: npm install - name: Build type declarations run: tsc --emitDeclarationOnly --declarationDir ./dist/types ./src/**/*.dto.ts ./src/**/*.entity.ts - name: Push to frontend repo uses: ad-m/github-push-action@master with: repository: <前端仓库地址> branch: main directory: ./dist/types target-directory: src/shared-types github_token: ${{ secrets.FRONTEND_REPO_TOKEN }} - 优势:前端无需手动操作,自动获取最新类型;类型直接来自后端编译结果,准确性有保障;不需要额外维护私有包。
方案3:自定义脚本从后端源码提取类型
- 编写Node.js脚本,通过TypeScript AST解析器(如
@typescript-eslint/parser)扫描后端的Nest.js实体、DTO文件,过滤掉后端特有的装饰器、逻辑代码,提取纯类型定义生成前端可用的.d.ts文件。 - 简化示例脚本:
import fs from 'fs'; import { parse, AST_NODE_TYPES } from '@typescript-eslint/parser'; function extractTypeFromFile(filePath: string) { const content = fs.readFileSync(filePath, 'utf-8'); const ast = parse(content, { parserOptions: { ecmaVersion: 'latest', sourceType: 'module' } }); // 遍历AST提取接口/类型别名定义,过滤Nest装饰器相关节点 const typeNodes = ast.body.filter(node => node.type === AST_NODE_TYPES.TSInterfaceDeclaration || node.type === AST_NODE_TYPES.TSTypeAliasDeclaration ); // 生成类型文件内容 return typeNodes.map(node => content.slice(node.range[0], node.range[1])).join('\n'); } const userType = extractTypeFromFile('./backend/src/dtos/user.dto.ts'); fs.writeFileSync('./frontend/src/shared-types/user.dto.d.ts', userType); - 优势:精准控制生成的类型,剔除后端冗余代码;类型完全适配前端使用场景,没有无关内容。
内容的提问来源于stack exchange,提问作者Kowalkox
相关产品推荐
相关产品推荐

