Some naming conventions promote the use of the underscore character ("_
") for those variables that must be declared but are not being used.
One common case is that in which a function signature contains some variables that will not be used, as for instance the Express error handlers:
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
In the above example only the arguments err
and res
are being used, though all four must be defined in the handler signature. Thus, following the naming convention of using underscores for those unused variables, we could recode it as:
app.use(function(err, _, res, __) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Though it makes the function more readable, it comes with a problem if using ESlint: it will blame by declaring unused variables.
error '_' is defined but never used
error '__' is defined but never used
We could avoid it by disabling the ESlint rule for those lines/blocks/files in which underscore variables are being used but, frankly, it makes the codebase dirtier and harder to maintain:
// eslint-disable-next-line no-unused-vars
app.use(function(err, _, res, __) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
There is however an elegant way of proceeding: Creating an ESlint rule that will apply to all our project. To do it, the .eslintrc
file must be edited and this rule must be added:
{
// .eslintrc directives
"rules": {
// .eslintrc rules
"no-unused-vars": [
"error",
{
"varsIgnorePattern": "^_+$",
"argsIgnorePattern": "^_+$"
}
]
}
}
The varsIgnorePattern
rule inhibits the ESlint unused variables error for those variables whose name matches the regular expression /^_+$/
, ie, those variables whose name was composed exclusively by one or more underscores. It also applies to the function arguments thanks to the argsIgnorePattern
rule.
If ESlint is dropping a warning instead of an error, it can be inhibited by replacing "error"
by "warn"
.
To know more about ESlint and its configuration, read Linting and formatting in Typescript.
Comentarios
Publicar un comentario