如何配置ESLint检查环境变量使用

解读

在国内前端团队的日常面试中,这道题表面问“配置”,实则考察三层能力:

  1. 是否意识到“环境变量”在代码里属于隐式全局,极易因拼写错误或运行时缺失导致上线事故;
  2. 能否把“业务规则”翻译成“ESLint 规则”,即让机器替人做 CR;
  3. 是否熟悉 ESLint 的插件化机制,能把规则无缝集成到 VS Code + Git Hooks + CI 的“国内标准三件套”。

如果候选人只回答“装个插件”,会被认为“用过但没落地”;如果能给出“自定义规则 + 统一配置包 + 多环境差异”的完整方案,基本锁定高分。

知识点

  1. 隐式全局与 no-undef:浏览器侧 process 未定义,Node 侧 window 未定义,环境变量拼写错误属于同类问题。
  2. ESLint 运行模型:Parser → Rule → Visitor Pattern,规则通过 context.report() 上报错误。
  3. 自定义规则入口:lib/rules/no-restricted-env-key.js 必须导出 meta.docs.url 与 create(context)。
  4. 共享配置(npm package)与 extends:国内大厂通常把规则包发布到私有 GitLab Package Registry,通过 @scope/eslint-config 统一收口。
  5. 环境差异:本地 .env.development、测试 .env.test、线上 .env.production,需要把“允许列表”拆成多份,通过 process.env.ESLINT_ENV 动态切换。
  6. 性能与缓存:自定义规则必须缓存 allowedKeys 数组,避免每次遍历 AST 都读磁盘。
  7. 集成链路: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 即刻暴露,真正做到“上线前零环境变量事故”。

拓展思考

  1. 如果项目使用 Vite,客户端代码通过 import.meta.env 访问变量,上述规则如何兼容?
    答:在 MemberExpression 里再判断 object.name === 'import' && property.name === 'meta',递归提取 env.xxx 即可;同时把 allowList 拆成“服务端”与“客户端”两份,通过 context.getFilename() 区分 src/server 与 src/client 目录。

  2. 如何防止“变量已声明但值硬编码密钥”?
    答:在自定义规则里追加 Literal 访问,若匹配 /sk-[a-zA-Z0-9]{48}/ 这类高熵字符串,直接报 no-hardcoded-secret,实现“变量名 + 值”双重校验。

  3. 规则性能如何优化到 1 万文件 3 秒跑完?
    答:把 allowList 在 eslint --cache 模式下序列化到 .eslintcache 的 meta 字段;第二次运行时直接读缓存,避免重复解析 .env.* 文件。

  4. 如何推动存量 200+ 项目一次性接入?
    答:基于国内公司常见的“基座工程”思路,把 @company/eslint-config 做成 create-foo-app 的 preset,配合 eslint-config-foo migrate 命令,自动扫描 process.env.* 出现过的所有 key,反向生成 allowList,实现“一键迁移 + 零误报”。

把以上四点想透,面试时主动抛出,基本可以让面试官停止追问,直接进入谈薪环节。