You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置ESLint规则强制console语句始终单行书写?

强制console调用单行书写的ESLint自定义规则

出于个人需求,我希望console.log、console.error等所有console调用语句始终保持单行书写。请问是否有经过验证且可用的ESLint规则?我自行编写的规则如下,但存在一些不明语法问题:

module.exports = {
  meta: {
    fixable: 'code',
  },
  create(context) {
    return {
      CallExpression(node) {
        if (
          node.callee.object &&
          node.callee.object.name === 'console' &&
          node.callee.property
        ) {
          const sourceCode = context.getSourceCode()
          const text = sourceCode.getText(node)

          // Check if there are comments inside the console statement
          const comments = sourceCode.getCommentsInside(node)

          if (text.includes('\n')) {
            if (comments.length > 0) {
              // Raise a warning if there are comments inside
              context.report({
                node,
                message:
                  'console.' +
                  node.callee.property.name +
                  ' contains comments and should be checked manually',
              })
            } else {
              // Fix the text if there are no comments
              context.report({
                node,
                message:
                  'console.' +
                  node.callee.property.name +
                  ' should be in one line',
                fix(fixer) {
                  const fixedText = text.replace(/\n/g, ' ').replace(/\s+/g, ' ')
                  return fixer.replaceText(node, fixedText)
                },
              })
            }
          }
        }
      },
    }
  },
}

目前没有官方或社区广泛维护的现成规则专门实现这个需求,但可以修正你写的自定义规则,解决语法和逻辑问题后即可正常使用。

修正后的可用规则

module.exports = {
  meta: {
    type: 'layout',
    fixable: 'whitespace',
    messages: {
      singleLine: 'console.{{method}} should be written in a single line',
      hasComments: 'console.{{method}} contains comments; please check manually',
    },
  },
  create(context) {
    return {
      CallExpression(node) {
        // 仅匹配直接的 console.method() 调用
        if (
          node.callee.type === 'MemberExpression' &&
          node.callee.object.type === 'Identifier' &&
          node.callee.object.name === 'console' &&
          node.callee.property.type === 'Identifier'
        ) {
          const sourceCode = context.getSourceCode();
          const methodName = node.callee.property.name;
          const nodeText = sourceCode.getText(node);
          const hasNewlines = nodeText.includes('\n');
          const innerComments = sourceCode.getCommentsInside(node);

          if (hasNewlines) {
            if (innerComments.length > 0) {
              context.report({
                node,
                messageId: 'hasComments',
                data: { method: methodName },
              });
            } else {
              context.report({
                node,
                messageId: 'singleLine',
                data: { method: methodName },
                fix(fixer) {
                  // 替换换行及前后空白为单个空格,再合并连续空格
                  const fixedText = nodeText.replace(/\s*\n\s*/g, ' ').replace(/\s+/g, ' ');
                  return fixer.replaceText(node, fixedText);
                },
              });
            }
          }
        }
      },
    };
  },
};

关键优化点

  • 严谨的节点匹配:明确检查节点类型,避免误判非直接console.xxx()的调用(比如解构赋值后的console变量、链式调用等)
  • 规范消息管理:使用messageId统一管理提示文案,符合ESLint规则的标准写法
  • 修复空格处理逻辑:优化正则表达式,替换换行及前后的空白为单个空格,再合并连续空格,避免破坏代码结构或产生多余空格
  • 完善meta配置:添加type: 'layout'明确规则类型,fixable设为whitespace更贴合规则的修复场景

使用方法

  1. 将规则保存为项目内的自定义规则文件(例如./eslint-rules/console-single-line.js)
  2. 在ESLint配置文件中引入规则:
{
  "plugins": [
    "custom"
  ],
  "rules": {
    "custom/console-single-line": "error"
  },
  "settings": {
    "import/resolver": {
      "node": {
        "paths": ["./eslint-rules"]
      }
    }
  }
}

根据你的项目结构调整插件路径配置即可。

内容的提问来源于stack exchange,提问作者til

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 16:33:13