如何在NestJS中创建可复用内部npm依赖模块库?
基于NestJS的公司级可复用模块库实现方案
一、代码结构规划
1. 采用Monorepo结构(适配Lerna/Nx)
沿用你熟悉的Lerna来管理多包仓库,核心结构如下:
company-nest-libs/ ├── packages/ │ ├── auth/ # @company-name/auth 模块 │ │ ├── src/ │ │ │ ├── index.ts # 导出所有对外API(模块、服务、DTO等) │ │ │ ├── auth.module.ts │ │ │ ├── auth.service.ts │ │ │ ├── dto/ │ │ │ └── guards/ │ │ ├── package.json │ │ ├── tsconfig.json │ │ └── nest-cli.json │ ├── cache/ # @company-name/cache 模块 │ │ ├── src/ │ │ │ ├── index.ts │ │ │ ├── cache.module.ts │ │ │ └── cache.service.ts │ │ └── ...(同auth的配置文件) │ └── logger/ # @company-name/logger 模块 │ └── ... ├── lerna.json ├── package.json └── tsconfig.base.json # 所有模块共享的TypeScript基础配置
2. 每个模块遵循NestJS规范
- 每个模块的
tsconfig.json继承根目录的tsconfig.base.json,保证编译规则统一 - 在模块的
src/index.ts中仅暴露公共API,私有代码不对外导出,示例:export * from './auth.module'; export * from './auth.service'; export * from './guards/jwt-auth.guard'; export * from './dto/login.dto'; - 每个模块独立配置
nest-cli.json,确保编译输出的dist目录结构符合NestJS包标准
3. 开启统一版本模式
在lerna.json中启用固定版本模式,让所有@company-name/*模块共享同一版本号,和Angular的包版本机制一致:
{ "packages": ["packages/*"], "version": "1.0.0", "npmClient": "npm", "command": { "publish": { "registry": "https://npm.yourcompany.com" // 公司私有npm源地址 } } }
二、发布与复用流程
1. 配置私有npm源(必选)
公司内部使用时,搭建私有npm仓库(如Verdaccio),在根目录的.npmrc中配置:
@company-name:registry=https://npm.yourcompany.com registry=https://registry.npmmirror.com // 公共包镜像加速
2. 编译模块
每个模块的package.json配置编译脚本与输出指向:
{ "name": "@company-name/auth", "version": "1.0.0", "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "build": "nest build" }, "dependencies": { "@nestjs/jwt": "^10.1.0" }, "peerDependencies": { "@nestjs/common": "^10.0.0" } }
- 用
peerDependencies声明对NestJS核心包的依赖,避免业务项目重复安装同版本依赖 - 根目录执行
lerna run build批量编译所有模块
3. 版本升级与发布
- 版本迭代时,执行
lerna version [major/minor/patch],Lerna会自动更新所有模块的版本号并生成Git标签 - 发布执行
lerna publish from-git,所有模块将以同一版本号发布到私有npm源
4. 业务项目中使用
在项目的package.json中统一版本安装:
{ "dependencies": { "@company-name/auth": "^1.0.0", "@company-name/cache": "^1.0.0", "@company-name/logger": "^1.0.0" } }
然后在NestJS项目中导入使用:
import { Module } from '@nestjs/common'; import { AuthModule } from '@company-name/auth'; import { CacheModule } from '@company-name/cache'; @Module({ imports: [AuthModule.register({ secret: process.env.JWT_SECRET }), CacheModule], }) export class AppModule {}
内容的提问来源于stack exchange,提问作者Oxenarf
相关产品推荐
相关产品推荐

