Skip to content

Commit

Permalink
Fix: extend fixer range of prefer const to whole declaration
Browse files Browse the repository at this point in the history
  • Loading branch information
snitin315 committed Jan 24, 2021
1 parent f6602d5 commit ae87625
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
22 changes: 18 additions & 4 deletions lib/rules/prefer-const.js
Expand Up @@ -5,6 +5,11 @@

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const FixTracker = require("./utils/fix-tracker");
const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
Expand Down Expand Up @@ -451,10 +456,19 @@ module.exports = {
messageId: "useConst",
data: node,
fix: shouldFix
? fixer => fixer.replaceText(
sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind),
"const"
)
? fixer => {
const letKeywordToken = sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind);


/**
* Extend the replacement range to the whole declaration,
* in order to prevent other fixes in the same pass
* https://github.com/eslint/eslint/issues/13899
*/
return new FixTracker(fixer, sourceCode)
.retainRange(varDeclParent.range)
.replaceTextRange(letKeywordToken.range, "const");
}
: null
});
});
Expand Down
7 changes: 7 additions & 0 deletions tests/lib/rules/prefer-const.js
Expand Up @@ -546,6 +546,13 @@ ruleTester.run("prefer-const", rule, {
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" },
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" }
]
},

// https://github.com/eslint/eslint/issues/13899
{
code: "/*eslint no-undef-init:error*/ let foo = undefined;",
output: "/*eslint no-undef-init:error*/ const foo = undefined;",
errors: 2
}
]
});

0 comments on commit ae87625

Please sign in to comment.