简体   繁体   English

如何使用 ESlint 禁止特定的命名函数

[英]How to forbid a specific named function with ESlint

The Situation情况

In our current project we've had some recurring problems with people using 'asMutable' from seamless-immutable where it isn't actually necessary.在我们当前的项目中,我们遇到了一些反复出现的问题,人们在无缝不可变的情况下使用“asMutable”,但实际上并不需要。 This has resulted in 'search project for string "asMutable"' becoming part of every pull request.这导致“字符串“asMutable”的搜索项目”成为每个拉取请求的一部分。 To speed this up we would like to add a rule warning that to our eslint.为了加快速度,我们想在我们的 eslint 中添加一个规则警告。 But I haven't figured out how.但我还没想好怎么做。

The Question问题

What seems like the best solution to me right now, though I'm open to suggestions, is a rule that allows me to specify a function name to forbid.尽管我愿意接受建议,但现在对我来说似乎最好的解决方案是允许我指定要禁止的函数名称的规则。 Does ESlint, or a plugin therefore, have that sort of functionality? ESlint 或插件是否具有这种功能?

Additional Notes附加说明

I've looked a little into writing our own, but I was intimidated by AST and the startup difficulty to writing my first rule.我曾考虑过编写自己的规则,但我被AST和编写我的第一条规则的启动困难吓倒了。 I may take the plunge if I can't find a better answer, yes we're getting this enough in PRs to warrant it.如果我找不到更好的答案,我可能会冒险尝试,是的,我们在 PR 中得到了足够的信息来保证它。 This seems like something someone much smarter than me has already solved though, so I'd rather follow in their footsteps then build my own.这似乎是比我更聪明的人已经解决的问题,所以我宁愿追随他们的脚步,然后建立自己的。

I had the same problem not so long ago so I can help you with writing your own.不久前我遇到了同样的问题,所以我可以帮助您编写自己的。

So, first, let's explain some basic structures:所以,首先,让我们解释一些基本结构:

  1. ESLint has plugins , and each plugin has rules . ESLint插件,每个插件都有规则
  2. ESLint uses AST which is a syntax tree to find specific parts in the code. ESLint使用AST语法树来查找代码中的特定部分。 This helps ESLint find what each rule is looking for.这有助于 ESLint 找到每个规则正在寻找的内容。

So, let's start by creating a plugin with a rule in it:因此,让我们首先创建一个带有规则的插件:


1. Use The ESLint Generator for Yeoman 1. 为 Yeoman 使用 ESLint 生成器

This makes things a lot easier.这让事情变得容易多了。 Check it out here .在这里查看

After you install yeoman and the yeoman eslint generator :安装yeomanyeoman eslint generator

  • go into the folder you want to create your project in进入您要在其中创建项目的文件夹
  • run yo eslint:plugin to create a new ESLint plugin运行yo eslint:plugin创建一个新的ESLint插件
  • after creating the plugin, run yo eslint:rule in the same folder创建插件后,在同一文件夹中运行yo eslint:rule

I used suni as the plugin name, and check-as-mutable as the rule name.我使用suni作为插件名称,并使用check-as-mutable作为规则名称。 Now we have all the initial files we need to write the rule.现在我们有了编写规则所需的所有初始文件。


2. Know what you need to look for using AST Explorer 2. 了解使用 AST Explorer 需要查找的内容

AST Explorer Can help us find what type of thing we're looking for. AST Explorer可以帮助我们找到我们正在寻找的东西类型 This is important so we can tell ESLint what in the code we want our function to run on.这很重要,因此我们可以告诉ESLint我们希望函数在代码中运行的内容。

When you paste code into AST Explorer , it shows you what ESLint is seeing.当您将代码粘贴到AST Explorer 中时,它会向您显示ESLint所看到的内容。 We want to target all MemberExpression s:我们要针对所有MemberExpression

something. asMutable (); asMutable ();

Inside that, we want the Identifier node to check the function name在里面,我们希望Identifier node检查函数名称


3. Write the plugin itself 3. 编写插件本身

Open lib/rules/check-as-mutable.js and check it out.打开lib/rules/check-as-mutable.js并检查它。 All the data you provided for Yeoman was used to fill some fields here.您为Yeoman提供的所有数据都用于填写此处的某些字段。

Inside the rule, you have a create attribute.在规则内部,您有一个create属性。 Here, we write our code.在这里,我们编写我们的代码。 This function should return an object, with what we want our rules to run on as attributes.这个函数应该返回一个对象,我们希望我们的规则作为属性运行。 So, in this case, it will look like so:所以,在这种情况下,它看起来像这样:

create: function(context) {

    return {
      MemberExpression: function(node)...

    };
}

While writing the rule, you should check which fields you need using the AST Explorer .在编写规则时,您应该使用AST Explorer检查您需要哪些字段。

here is the implementation:这是实现:

create: function(context) {
  var UNWANTED_FUNCTION_NAME = 'asMutable';
  return {
    MemberExpression: function reportUnwantedName(node) {
      var functionName = node.property.name;

      if (functionName === UNWANTED_FUNCTION_NAME) {
        context.report({
          node: node,
          message: [
            'Please don\'t use ',
            UNWANTED_FUNCTION_NAME,
            '. We don\'t like it!'].join('')
        });
      }
    }
  };
}

After that, you need to install the plugin in your project.之后,您需要在项目中安装插件。 To do that, upload it to GitHub, and install it using npm:为此,请将其上传到 GitHub,并使用 npm 进行安装:

npm install --save-dev <user_name>/<repository_name>

And include the rule in your .eslintrc file as well:并将规则也包含在您的.eslintrc文件中:

{
    'plugins': ['suni'],
    'rules': {
      'suni/check-as-mutable': 1
    }
}

Notice that I gave it the value 1 .请注意,我给了它值1 This makes this rule show as a Warning and not as an Error这使得此规则显示为警告而不是错误

在此处输入图片说明

Notice that the warning highlights the Immutable itself, since that is the node we pass to context.report .请注意,警告突出显示了 Immutable 本身,因为它是我们传递给context.reportnode You can tweak that to highlight the id node instead.您可以调整它以突出显示id node

Here's the plugin I created for this answer这是我为此答案创建的插件

Good luck!祝你好运!

You can do some very fancy things when you combine ESLint's no-restricted-syntax rule with selectors .当你将 ESLint 的no-restricted-syntax规则与selectors结合起来时,你可以做一些非常奇特的事情。 In your case you should be able to achieve the linting you want without writing your own plugin.在您的情况下,您应该能够在不编写自己的插件的情况下实现所需的 linting。 The rule would look something like:该规则类似于:

{
  rules: {
    'no-restricted-syntax': [
      'error',
      {
        message: "Please don't use asMutable. We don't like it!",
        selector:
          'MemberExpression > Identifier[name="asMutable"]'
      }
    ]
  }
}

Study the documentation page for selectors ;研究selectors的文档页面; it is very flexible!它非常灵活!

On top of @Eric Simonton's answer , since ESLint 3.5.0 we have the purpose-built no-restricted-properties :@Eric Simonton 的回答之上,从 ESLint 3.5.0 开始,我们有专门构建的无限制属性

"no-restricted-properties": [ "error", {
    "object": "Immutable",
    "property": "asMutable",
    "message": "optional explanation to the recurring problems we've had"
}]

If anyone comes here looking for ways to block functions that aren't class methods, you can similarly use no-restricted-globals如果有人来这里寻找阻止不是类方法的函数的方法,您可以类似地使用no-restricted-globals

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

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