如何配置ESLint检查环境变量使用
解读
在国内前端团队的日常面试中,这道题表面问“配置”,实则考察三层能力:
- 是否意识到“环境变量”在代码里属于隐式全局,极易因拼写错误或运行时缺失导致上线事故;
- 能否把“业务规则”翻译成“ESLint 规则”,即让机器替人做 CR;
- 是否熟悉 ESLint 的插件化机制,能把规则无缝集成到 VS Code + Git Hooks + CI 的“国内标准三件套”。
如果候选人只回答“装个插件”,会被认为“用过但没落地”;如果能给出“自定义规则 + 统一配置包 + 多环境差异”的完整方案,基本锁定高分。
知识点
- 隐式全局与 no-undef:浏览器侧
process未定义,Node 侧window未定义,环境变量拼写错误属于同类问题。 - ESLint 运行模型:Parser → Rule → Visitor Pattern,规则通过
context.report()上报错误。 - 自定义规则入口:
lib/rules/no-restricted-env-key.js必须导出meta.docs.url与create(context)。 - 共享配置(npm package)与
extends:国内大厂通常把规则包发布到私有 GitLab Package Registry,通过@scope/eslint-config统一收口。 - 环境差异:本地
.env.development、测试.env.test、线上.env.production,需要把“允许列表”拆成多份,通过process.env.ESLINT_ENV动态切换。 - 性能与缓存:自定义规则必须缓存
allowedKeys数组,避免每次遍历 AST 都读磁盘。 - 集成链路:VS Code 插件 →
eslint.rules.customizations做实时红线;husky + lint-staged 做本地拦截;GitLab CI 的eslint --max-warnings=0做门禁。
答案
下面给出“开箱即用”的落地级方案,分四步完成,全部代码可直接搬进国内项目。
第一步:新建自定义规则包(推荐放到 packages/eslint-plugin-env 私有目录)
// packages/eslint-plugin-env/lib/rules/no-restricted-env-key.js
const fs = require('fs');
const path = require('path');
module.exports = {
meta: {
type: 'problem',
docs: {
description: '禁止在生产环境使用未声明的环境变量',
category: 'Possible Errors',
recommended: true,
url: 'https://git.company.com/frontend/eslint-plugin-env'
},
schema: [{
type: 'object',
properties: {
allowList: { type: 'array', items: { type: 'string' } },
cwd: { type: 'string' }
},
additionalProperties: false
}],
messages: {
restrictedKey: '环境变量 "{{key}}" 未在 allowList 中声明,拼写错误或存在泄露风险。'
}
},
create(context) {
const options = context.options[0] || {};
const allowList = options.allowList || [];
const cwd = options.cwd || process.cwd();
// 支持动态加载多环境列表
const envFile = path.resolve(cwd, `.env.${process.env.ESLINT_ENV || 'production'}`);
if (fs.existsSync(envFile)) {
const content = fs.readFileSync(envFile, 'utf8');
content.split('\n').forEach(line => {
const key = line.split('=')[0].trim();
if (key && !allowList.includes(key)) allowList.push(key);
});
}
return {
MemberExpression(node) {
if (
node.object.name === 'process' &&
node.property.name === 'env' &&
node.parent.type === 'MemberExpression' &&
node.parent.object === node
) {
const key = node.parent.property.name || node.parent.property.value;
if (!allowList.includes(key)) {
context.report({
node: node.parent.property,
messageId: 'restrictedKey',
data: { key }
});
}
}
}
};
}
};
第二步:在插件入口注册规则
// packages/eslint-plugin-env/index.js
module.exports = {
rules: {
'no-restricted-env-key': require('./lib/rules/no-restricted-env-key')
},
configs: {
recommended: {
plugins: ['@company/env'],
rules: {
'@company/env/no-restricted-env-key': ['error', {
allowList: ['NODE_ENV', 'PORT']
}]
}
}
}
};
第三步:业务项目一次性接入
# 安装
npm i -D @company/eslint-plugin-env @company/eslint-config-base
# .eslintrc.js
module.exports = {
extends: [
'@company/eslint-config-base', // 已经包含 parser、import、react 等通用规则
'plugin:@company/env/recommended'
],
parserOptions: {
ecmaVersion: 2022,
sourceType: 'module'
},
env: {
node: true,
browser: true
}
};
第四步:多环境差异与 CI 集成
# package.json 脚本
"scripts": {
"lint:dev": "ESLINT_ENV=development eslint .",
"lint:test": "ESLINT_ENV=test eslint .",
"lint": "ESLINT_ENV=production eslint . --max-warnings=0"
}
# GitLab CI
lint:
stage: check
image: node:18-alpine
script:
- npm ci
- npm run lint
only:
- merge_requests
至此,任何人在代码里写 process.env.UNKOWN_KEY 都会被实时标红,MR 无法合并;若变量名拼错,本地 npm run lint:dev 即刻暴露,真正做到“上线前零环境变量事故”。
拓展思考
-
如果项目使用 Vite,客户端代码通过
import.meta.env访问变量,上述规则如何兼容?
答:在MemberExpression里再判断object.name === 'import' && property.name === 'meta',递归提取env.xxx即可;同时把allowList拆成“服务端”与“客户端”两份,通过context.getFilename()区分src/server与src/client目录。 -
如何防止“变量已声明但值硬编码密钥”?
答:在自定义规则里追加Literal访问,若匹配/sk-[a-zA-Z0-9]{48}/这类高熵字符串,直接报no-hardcoded-secret,实现“变量名 + 值”双重校验。 -
规则性能如何优化到 1 万文件 3 秒跑完?
答:把allowList在eslint --cache模式下序列化到.eslintcache的meta字段;第二次运行时直接读缓存,避免重复解析.env.*文件。 -
如何推动存量 200+ 项目一次性接入?
答:基于国内公司常见的“基座工程”思路,把@company/eslint-config做成create-foo-app的 preset,配合eslint-config-foo migrate命令,自动扫描process.env.*出现过的所有 key,反向生成allowList,实现“一键迁移 + 零误报”。
把以上四点想透,面试时主动抛出,基本可以让面试官停止追问,直接进入谈薪环节。