Visitar URL original
fix: prefer-template invalid autofix creates a tagged template call (… · eslint/eslint@684b579 · GitHub
Skip to content

Commit 684b579

Browse files
authored
fix: prefer-template invalid autofix creates a tagged template call (#21207)
fix: prevent ASI hazard in prefer-template autofix
1 parent 55db479 commit 684b579

2 files changed

Lines changed: 56 additions & 1 deletion

File tree

‎lib/rules/prefer-template.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,9 +299,15 @@ module.exports = {
299299
return null;
300300
}
301301

302+
const prefix =
303+
astUtils.isStartOfExpressionStatement(topBinaryExpr) &&
304+
astUtils.needsPrecedingSemicolon(sourceCode, topBinaryExpr)
305+
? ";"
306+
: "";
307+
302308
return fixer.replaceText(
303309
topBinaryExpr,
304-
getTemplateLiteral(topBinaryExpr, null, null),
310+
`${prefix}${getTemplateLiteral(topBinaryExpr, null, null)}`,
305311
);
306312
}
307313

‎tests/lib/rules/prefer-template.js‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,5 +419,54 @@ ruleTester.run("prefer-template", rule, {
419419
output: `\`${"\\".repeat(1_000_000)}\${ test}\``,
420420
errors,
421421
},
422+
423+
// preceding semicolon needed
424+
{
425+
code: "foo\n'bar' + baz",
426+
output: "foo\n;`bar${ baz}`",
427+
errors,
428+
},
429+
{
430+
code: "foo()\n'bar' + baz",
431+
output: "foo()\n;`bar${ baz}`",
432+
errors,
433+
},
434+
{
435+
code: "foo[0]\n'bar' + baz",
436+
output: "foo[0]\n;`bar${ baz}`",
437+
errors,
438+
},
439+
{
440+
code: "`template`\n'bar' + baz",
441+
output: "`template`\n;`bar${ baz}`",
442+
errors,
443+
},
444+
{
445+
code: "'qux'\n'bar' + baz",
446+
output: "'qux'\n;`bar${ baz}`",
447+
errors,
448+
},
449+
450+
// preceding semicolon not needed
451+
{
452+
code: "foo;\n'bar' + baz",
453+
output: "foo;\n`bar${ baz}`",
454+
errors,
455+
},
456+
{
457+
code: "if (foo) {}\n'bar' + baz",
458+
output: "if (foo) {}\n`bar${ baz}`",
459+
errors,
460+
},
461+
{
462+
code: "'bar' + baz",
463+
output: "`bar${ baz}`",
464+
errors,
465+
},
466+
{
467+
code: "foo\nconsole.log('bar' + baz)", // not at the start of an expression statement
468+
output: "foo\nconsole.log(`bar${ baz}`)",
469+
errors,
470+
},
422471
],
423472
});

0 commit comments

Comments
 (0)