【问题标题】:is there way to lint a specific variable name with eslint有没有办法用 eslint 对特定的变量名进行 lint
【发布时间】:2016-12-30 14:08:00
【问题描述】:

例如,我想删除一个特定的变量名,如 $abc 或 '$abc',如果它存在于任何地方,我们将抛出一个 linting 错误。它专门用于 es6 代码或只是 javascript 代码。

如何在 eslint 中做到这一点?有可能吗?

如果不是,我可以做些什么来检查而不污染我的代码库?

【问题讨论】:

标签: javascript ecmascript-6 lint eslint


【解决方案1】:

您可以按照 cmets 中的说明创建 your own eslint rule。这是一个小示例,它报告名称为 foo 的所有标识符(不包括属性名称):

export default function(context) {
  return {
    Identifier(node) {
      if (
        node.name === 'foo' && 
        (
          node.parent.type !== 'MemberExpression' ||
          node.parent.computed ||
          node.parent.object === node
        )
      ) {
        context.report(node, 'Do not use the variable name "foo"');
      }
    }
  };
};

现场示例:http://astexplorer.net/#/Lmzgbm2iRq

【讨论】:

    【解决方案2】:

    您可以遍历代码库并检查所有文件中是否存在您希望消除的变量。对于您需要的东西,它可能有点重量级,但它可能是一种选择。

    这样的事情应该可以解决问题。您必须将 $bad_variable_name 替换为您的实际值 变量是。您还必须做一些事情来使您的构建失败(如果需要)

    var fs = require('fs');
    var checkDir = (dir) => {   
      var files = fs.readdirSync(dir);
      files.forEach((file) => {
        var path = dir + '/' + file;
        var stat = fs.statSync(path);
        if (stat && stat.isDirectory()) {
          checkDir(path);
        } else {
          if(path.endsWith('this-file.js')){ //the file where this code is
            return;
          }
          var fileContents = fs.readFileSync(path);
          if(fileContents.indexOf('$bad_variable_name') > -1){ 
            console.log('$bad_variable_name found in ' + path);                 
            //do something here to fail your build
          }
        }
      });
    };
    

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2022-12-13
      • 2022-01-22
      • 2016-01-16
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      相关资源
      最近更新 更多