Skip to content

Commit fb27422

Browse files
authored
Fix: extend prefer-const fixer range to whole declaration (fixes #13899) (#14033)
* Fix: extend fixer range of prefer const to whole declaration * Chore: update prefer-const test case
1 parent e0b05c7 commit fb27422

2 files changed

Lines changed: 27 additions & 5 deletions

File tree

lib/rules/prefer-const.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55

66
"use strict";
77

8+
//------------------------------------------------------------------------------
9+
// Requirements
10+
//------------------------------------------------------------------------------
11+
12+
const FixTracker = require("./utils/fix-tracker");
813
const astUtils = require("./utils/ast-utils");
914

1015
//------------------------------------------------------------------------------
@@ -451,10 +456,18 @@ module.exports = {
451456
messageId: "useConst",
452457
data: node,
453458
fix: shouldFix
454-
? fixer => fixer.replaceText(
455-
sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind),
456-
"const"
457-
)
459+
? fixer => {
460+
const letKeywordToken = sourceCode.getFirstToken(varDeclParent, t => t.value === varDeclParent.kind);
461+
462+
/**
463+
* Extend the replacement range to the whole declaration,
464+
* in order to prevent other fixes in the same pass
465+
* https://github.com/eslint/eslint/issues/13899
466+
*/
467+
return new FixTracker(fixer, sourceCode)
468+
.retainRange(varDeclParent.range)
469+
.replaceTextRange(letKeywordToken.range, "const");
470+
}
458471
: null
459472
});
460473
});

tests/lib/rules/prefer-const.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -500,9 +500,11 @@ ruleTester.run("prefer-const", rule, {
500500
{ message: "'b' is never reassigned. Use 'const' instead.", type: "Identifier" }
501501
]
502502
},
503+
504+
// The inner `let` will be auto-fixed in the second pass
503505
{
504506
code: "let someFunc = () => { let a = 1, b = 2; foo(a, b) }",
505-
output: "const someFunc = () => { const a = 1, b = 2; foo(a, b) }",
507+
output: "const someFunc = () => { let a = 1, b = 2; foo(a, b) }",
506508
errors: [
507509
{ message: "'someFunc' is never reassigned. Use 'const' instead.", type: "Identifier" },
508510
{ message: "'a' is never reassigned. Use 'const' instead.", type: "Identifier" },
@@ -546,6 +548,13 @@ ruleTester.run("prefer-const", rule, {
546548
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" },
547549
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" }
548550
]
551+
},
552+
553+
// https://github.com/eslint/eslint/issues/13899
554+
{
555+
code: "/*eslint no-undef-init:error*/ let foo = undefined;",
556+
output: "/*eslint no-undef-init:error*/ const foo = undefined;",
557+
errors: 2
549558
}
550559
]
551560
});

0 commit comments

Comments
 (0)