8
votes

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.

1
If you use a JavaScript config file, does the /[A-Z][a-z]*Model/ regex syntax work?ssube
So rename my .eslintrc basically?Warren P
That's what I would try. Some (most?) tools just load their config with require, so you can often use a JS file instead of JSON. It's great for returning different configs if you do the env == PROD thing from Rails, but obviously allows real RegExps as well. It's just a matter of whether the consuming tool will recognize and use them.ssube
eslintrc.js like this, doesn't work: module.exports = { "extends": "eslint:recommended", "env": { "browser": true }, "globals": { /[A-Z][a-z]*Model/: true, ...Warren P

1 Answers

5
votes

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.