自定义 ESLint 规则禁止 console.log 但允许 console.error

解读

国内一线团队普遍把「零 console.log 上线」写进规范,因为生产环境残留的普通日志会泄露调试信息、污染 Sentry 与埋点数据,甚至拖慢低端机性能。
但保留 console.error 是刚需:灰度阶段、客户端 WebView 白屏、用户反馈无法复现等场景,仍需用 error 级别日志快速定位问题。
因此面试官想确认两点:

  1. 你是否理解 ESLint 的规则运行机制(AST 遍历、context.report、fixer);
  2. 你是否能把「业务诉求」翻译成「可落地的工程化方案」,并兼顾可维护性与可迁移性。

知识点

  • ESLint Rule 五件套:meta.schema、meta.messages、create、context、fixer
  • AST 节点类型:CallExpression、MemberExpression、Identifier
  • 作用域与引用解析:context.getScope()、Reference.isRead()
  • 国内 Monorepo 场景:规则需发布到私有 npm,并在**@company/eslint-config** 中统一收口
  • 性能红线:遍历深度 ≤3 层、避免正则、缓存节点类型判断,防止Webpack 热更新阶段卡死
  • 与 CI 集成:在GitLab-CI / GitHub Actions中通过 --max-warnings=0 强制红线,禁止 --no-lint 绕过

答案

  1. 初始化规则文件
    在 @company/eslint-plugin-no-console-log 包中新建 lib/rules/no-console-log.js:
module.exports = {
  meta: {
    type: 'problem',
    docs: {
      description: '禁止 console.log,但允许 console.error',
      recommended: true,
    },
    schema: [], // 无参数
    messages: {
      unexpected: '生产环境禁止 console.log,请使用日志上报或 console.error',
    },
  },
  create(context) {
    return {
      CallExpression(node) {
        const callee = node.callee;
        // 判断是否为 console.log()
        if (
          callee.type === 'MemberExpression' &&
          callee.object.name === 'console' &&
          callee.property.name === 'log'
        ) {
          context.report({
            node,
            messageId: 'unexpected',
            // 可选:提供自动修复,直接删除该行
            fix(fixer) {
              return fixer.remove(node.parent.type === 'ExpressionStatement' ? node.parent : node);
            },
          });
        }
      },
    };
  },
};
  1. 注册插件
    在 index.js 中导出规则:
module.exports = {
  rules: {
    'no-console-log': require('./lib/rules/no-console-log'),
  },
};
  1. 在团队共享配置中启用
    在 @company/eslint-config 的 index.js 里:
module.exports = {
  plugins: ['@company/no-console-log'],
  rules: {
    '@company/no-console-log/no-console-log': 'error',
  },
};
  1. 发布与集成

    • 私有 npm 发布:pnpm publish --registry=https://npm.company.com
    • 项目侧安装:pnpm add -D @company/eslint-config @company/eslint-plugin-no-console-log
    • CI 卡点:eslint . --max-warnings=0 失败即阻断合并
  2. 灰度策略
    对存量项目采用 warning → error 双阶段:

    • 第一阶段:warn + husky pre-commit 提示
    • 第二阶段:全量 error,配合代码巡检平台自动提 MR 清理旧代码

拓展思考

  1. 动态级别控制
    通过 schema 开放白名单,例如允许 console.warn 在测试环境出现,实现「一套规则,多环境差异化」。

  2. 与埋点系统打通
    在 fixer 里把 console.log 自动替换成 window.$logger.debug,直接收敛到统一日志平台,避免开发者手动改代码。

  3. AST 性能优化
    对大型文件(>2k 行)可做短路判断:先检测 console 变量是否被重新赋值,若无则跳过后续遍历,减少 30% lint 耗时。

  4. 结合 TypeScript
    若项目用 TS,可在规则里调用 context.parserServices.program.getTypeChecker(),精确识别 log 方法是否来自全局 console,防止误杀自定义 class Console {} 的合法调用。

  5. 未来演进
    随着WebAssembly与Worker普及,日志可能出现在不同线程;规则可扩展为跨文件链路分析,确保 console.log 在主线程、Worker、WASM 内均被禁止,形成全链路日志治理闭环。