alecxe alecxe - 5 months ago 16
Node.js Question

Catching all declared variables in ESLint

The Story:

Currently, I'm developing a specific

ESLint
rule (link) to catch all the places where there is a variable that shadows a built-in Protractor global variable, like
browser
or
element
.

Here is how the rule looks like at the moment:

module.exports = function (context) {
var protractorGlobals = [
'browser',
'protractor',
'element',
'by',
'$',
'$$'
]

function checkVariables (node) {
var variables = context.getDeclaredVariables(node)
for (var i = 0; i < variables.length; ++i) {
if (protractorGlobals.indexOf(variables[i].name) !== -1) {
context.report(node, 'Unexpected Protractor built-in global variable shadowing')
}
}
}

return {
'VariableDeclaration': checkVariables,
'FunctionDeclaration': checkVariables,
'FunctionExpression': checkVariables,
'CatchClause': checkVariables
}
}


As you can see, I'm looking for all variable and function declarations, function expressions, catch clauses and switch statements covering the following cases:

var browser = "something";
function test (browser) {};
var browser;
function browser () {};
var browser = 1;
for (var browser = 0; by < 10; ++by) {}
try { json = JSON.parse(input) } catch (browser) {}


The Question:

Have I covered all the places where a new variable is introduced in a current scope? Is there a more generic way to get declared variables anywhere in the code without guessing and explicitly defining the places to look for them?

Answer

If you support ES6, then you are missing import declarations. However, there's a slightly easier way to do this. ESLint uses package called Escope under the hood, to track variables declarations and usage. You can take a look at no-redeclare rule on how to access it, and refer to Escope documentation for information about API. Escope should allow you to check all variables in the current scope and see if you are re-declaring variable that already exists.