Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create an ESLint rule that will allow all globals matching a regular expression?

I am looking for an exception to the no-undef rule that will permit undeclared globals matching a naming rule. In this case, a regex like [A-Z][a-z]*Model should be allowed, so "CustomerModel" and "PatientModel" would all be allowed, because it's too cumbersome to place /* global CustomerModel */ in every unit and too cumbersome to list every *Model global even in the eslint global configuration.

I would like to have a rule like this:

"rules": {
        "no-undef": [2, "[A-Z][a-z]*Model"],

Where the above syntax is invented by me and I hope obviously means "only complain when the above reg-expression name is not matched."

Alternatively if there is a way to specify regular expression matching in the .eslintrc file globals list.

like image 973
Warren P Avatar asked Sep 27 '16 20:09

Warren P


People also ask

How do you set rules in ESLint?

ESLint comes with a large number of built-in rules and you can add more rules through plugins. You can modify which rules your project uses either using configuration comments or configuration files. To change a rule setting, you must set the rule ID equal to one of these values: "off" or 0 - turn the rule off.

What does 2 mean in ESLint rules?

I defines the severity of a rule. Severity should be one of the following: 0 = off, 1 = warning, 2 = error (you passed "3"). Documentation: https://eslint.org/docs/user-guide/configuring/rules.

How many ESLint rules are there?

Keep in mind that we have over 200 rules, and that is daunting both for end users and the ESLint team (who has to maintain them). As such, any new rules must be deemed of high importance to be considered for inclusion in ESLint.


1 Answers

Well, you could create your own rule, if you feel like it.

The source of the no-undef rule is pretty short. Probably you will need to replace the condition defined there

if (!considerTypeOf && hasTypeOfOperator(identifier)) {
    return;
}

with something like

if (/Model$/.test(identifier.name) || !considerTypeOf && hasTypeOfOperator(identifier)) {
    return;
}

To make sure that global identifiers ending with Model won't trigger the error.

You may also want to parameterize the identifier format rather than having it hard coded in the source. Since you are an experienced programmer, you will certainly be able to figure out the details and caveats of this approach yourself.

This is probably the most simple part of the job. It still takes some machinery to get your custom rule to work. More infos on how to create custom rules can be found here: http://eslint.org/docs/developer-guide/working-with-rules.

like image 113
GOTO 0 Avatar answered Sep 19 '22 07:09

GOTO 0