简体   繁体   English

有没有办法用eslint整理一个特定的变量名

[英]is there way to lint a specific variable name with eslint

For example, I want to eliminate a specific variable name like $abc or '$abc', if it exist anywhere, we will throw a linting error. 例如,我想消除一个特定的变量名,例如$ abc或'$ abc',如果它存在于任何地方,我们将抛出一个掉毛错误。 Its specifically for es6 code or just javascript code. 它专门用于es6代码或仅用于javascript代码。

How can I do that in eslint? 如何在eslint中做到这一点? is it possble? 有可能吗?

If its not what is the alternative I can do to check that without pollute my code base? 如果不是,我可以采取什么措施来检查代码而不污染我的代码库?

You can create your own eslint rule as mentioned in the comments. 您可以按照注释中的说明创建自己的eslint规则 Here is a small example that reports all identifiers (excluding property names) with name foo : 这是一个小示例,报告名称为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"');
      }
    }
  };
};

Live example: http://astexplorer.net/#/Lmzgbm2iRq 实时示例: http//astexplorer.net/#/Lmzgbm2iRq

You could traverse the codebase and check all the files for the presence of the variable you wish to eliminate. 您可以遍历代码库并检查所有文件中是否存在要消除的变量。 It's perhaps a bit heavyweight for what you need but it might be an option. 它可能满足您的需求,但它可能是一个选择。

Something like this should do the trick. 这样的事情应该可以解决问题。 You will have to replace $bad_variable_name with whatever your actual variable is. 您将必须用实际变量替换$ bad_variable_name。 You will also have to do something to make your build fail (if desired) 您还必须采取一些措施使构建失败(如果需要)

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
      }
    }
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM