Nest.js的模块化结构如何配置ESLint检查
解读
面试官抛出此题,核心想验证三件事:
- 你是否理解 Nest「模块即目录」的物理结构(每个模块含 .controller.ts、.service.ts、.module.ts、dto/.ts、entities/*.ts 等);
- 能否把 ESLint 的「规则层—配置层—集成层」映射到 Nest 工程,做到「模块级精准扫描、目录级渐进升级、CI 级卡点」;
- 是否熟悉国内落地场景:pnpm monorepo、husky + lint-staged、GitLab CI、阿里/腾讯代码规约、私有 Nexus 托管的 @company/eslint-config 共享包。
回答时切忌只贴一段 .eslintrc.js,而要展示「目录结构 → 多环境配置 → 增量扫描 → 性能优化 → 团队协作」的闭环思路。
知识点
-
物理分层与逻辑分层
apps/与libs/双轨(Nx、pnpm workspace)- 每个模块内部
index.ts作为 barrel,容易触发「循环依赖」与「barrel 爆炸」,需@typescript-eslint/no-cycle与import/no-self-import
-
多实例配置(Overrides)
- 对
*.controller.ts强制使用@typescript-eslint/explicit-function-return-type,防止隐式 any 污染 Swagger 类型 - 对
*.dto.ts关闭class-methods-use-this,因为 DTO 只有属性无方法 - 对
test/**/*关闭@typescript-eslint/no-non-null-assertion,允许 fixture 写user!.id
- 对
-
性能与增量
- 使用
eslint --cache --cache-location node_modules/.cache/eslint缓存,配合lint-staged只检查git diff列表,200 模块项目也能 3 s 内完成 - 在
.eslintignore中排除dist、webpack、prisma生成代码,避免误报
- 使用
-
国内私有共享配置
- 把公司级规则发布到内网 Nexus 的
@company/eslint-config-nest,继承@typescript-eslint/recommended-requiring-type-checking,再追加「禁止在 constructor 里写业务逻辑」等自定义规则 - 通过
require.resolve('@company/eslint-config-nest')保证团队成员一键同步,无需手动拷贝
- 把公司级规则发布到内网 Nexus 的
-
工程集成
- VS Code
.vscode/settings.json打开editor.codeActionsOnSave.source.fixAll.eslint: true,保存即自动排序 import 并修复可修复错误 - GitLab CI 阶段
lint:eslint: cache: key: "$CI_COMMIT_REF_SLUG",失败则阻断 merge - 与阿里云效/腾讯蓝盾集成时,把 ESLint 报告输出为
eslint-report.json,再用@serverless-cd/eslint-plugin做质量门禁
- VS Code
答案
下面给出一套可直接落地的「Nest + ESLint」配置流程,兼顾单仓库与 monorepo,全部基于国内常见工具链(pnpm、husky、GitLab CI)。
步骤 1:初始化
pnpm create nest-app my-nest
cd my-nest
pnpm add -D eslint @typescript-eslint/{parser,eslint-plugin} eslint-config-prettier eslint-plugin-import eslint-plugin-unused-imports husky lint-staged
步骤 2:目录约定(以 monorepo 为例)
my-nest/
├─ apps/
│ ├─ api/
│ │ ├─ src/user/{user.controller.ts,user.service.ts,user.module.ts}
│ │ └─ tsconfig.app.json
├─ libs/
│ ├─ shared/src/{dto,entities,guards}
│ └─ tsconfig.lib.json
├─ .eslintrc.js
├─ .eslintignore
├─ package.json
步骤 3:根配置 .eslintrc.js
require('@rushstack/eslint-patch/modern-module-resolution');
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2022,
sourceType: 'module',
project: ['./apps/*/tsconfig.app.json', './libs/*/tsconfig.lib.json'],
tsconfigRootDir: __dirname,
},
plugins: ['@typescript-eslint', 'import', 'unused-imports'],
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'@typescript-eslint/recommended-requiring-type-checking',
'prettier', // 必须放最后,关闭与 prettier 冲突的规则
],
rules: {
// 业务强约束
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/explicit-function-return-type': ['warn', { allowExpressions: true }],
'@typescript-eslint/no-floating-promises': 'error', // 防止忘记 await
'import/no-cycle': 'error', // 阻断循环依赖
'unused-imports/no-unused-imports': 'error',
// 关闭与 Nest 装饰器冲突的规则
'@typescript-eslint/no-parameter-properties': 'off',
},
overrides: [
{
files: ['*.controller.ts'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'error', // 强制返回类型,保障 Swagger
},
},
{
files: ['*.dto.ts', '*.entity.ts'],
rules: {
'class-methods-use-this': 'off',
},
},
{
files: ['**/*.spec.ts', '**/*.e2e-spec.ts'],
rules: {
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/unbound-method': 'off',
},
},
],
ignorePatterns: ['dist', 'node_modules', '*.js', 'coverage', 'prisma'],
};
步骤 4:package.json 脚本
{
"scripts": {
"lint": "eslint . --cache --max-warnings 0",
"lint:fix": "eslint . --fix --cache"
},
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix --cache", "git add"]
}
}
步骤 5:husky 预提交
npx husky install
npx husky add .husky/pre-commit 'npx lint-staged'
步骤 6:GitLab CI 卡点
lint:
stage: check
image: node:18-alpine
cache:
key: "$CI_COMMIT_REF_SLUG"
paths:
- node_modules/
- node_modules/.cache/
script:
- pnpm install --frozen-lockfile
- pnpm lint
only:
- merge_requests
步骤 7:私有共享配置(可选)
- 在内网 Nexus 新建 npm 仓库
@company/eslint-config-nest - 发布包内容仅含
index.js与package.json,index.js中module.exports = require('./.eslintrc.js') - 业务项目
.eslintrc.js简化为:
module.exports = {
extends: ['@company/eslint-config-nest'],
rules: {
// 项目差异化规则
},
};
至此,Nest 的模块化代码在任何子目录、任何 MR 阶段都能被 ESLint 精准扫描,缓存 + 增量保证 3 s 级反馈,私有共享配置保证团队规则一致,CI 门禁保证不合规代码无法进入主干。
拓展思考
-
若项目膨胀到 500+ 模块,eslint --cache 仍出现 10 s 以上耗时,可:
- 启用
EXPERIMENTAL_useProjectService: true(@typescript-eslint v6 实验功能),把类型检查做成长期守护进程 - 按「领域边界」拆成多个 eslintrc,用
root: true隔离,配合 pnpm --filter 并行 lint
- 启用
-
与 Nest CLI 的
webpack热重载结合:- 在
nest start --watch之前加eslint-webpack-plugin,把错误以 overlay 形式弹到浏览器,实现「编码即反馈」
- 在
-
自定义规则落地业务语义:
- 写一条
eslint-plugin-nestjs-rules禁止在@Injectable()里直接new Repository(),强制通过 DI 容器,彻底杜绝「new 出来的依赖无法 mock」的单元测试痛点
- 写一条
-
国内合规场景:
- 金融/政务项目需过「等保测评」,可在 ESLint 层拦截
console.log敏感字段,自定义规则扫描process.env.SECRET是否被明文打印,提前消灭审计漏洞
- 金融/政务项目需过「等保测评」,可在 ESLint 层拦截
-
未来趋势:
- ESLint 9 将彻底扁平化配置(flat config),Nest 官方脚手架已预留
eslint.config.js入口,提前研究typescript-eslint的 flat config 迁移方案,可在面试中展示「技术前瞻性」
- ESLint 9 将彻底扁平化配置(flat config),Nest 官方脚手架已预留