Skip to content

Commit

Permalink
flag useless nested template literals
Browse files Browse the repository at this point in the history
  • Loading branch information
kirkwaiblinger committed Mar 4, 2024
1 parent 6954a4a commit 8bdddbd
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/eslint-plugin/src/rules/no-useless-template-literals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,12 @@ export default createRule<[], MessageId>({
}

const fixableExpressions = node.expressions.filter(
(expression): expression is TSESTree.Literal | TSESTree.Identifier =>
expression =>
isLiteral(expression) ||
isUndefinedIdentifier(expression) ||
isInfinityIdentifier(expression) ||
isNaNIdentifier(expression),
isNaNIdentifier(expression) ||
expression.type === AST_NODE_TYPES.TemplateLiteral,
);

fixableExpressions.forEach(expression => {
Expand Down Expand Up @@ -145,6 +146,19 @@ export default createRule<[], MessageId>({
const escapedValue = stringValue.replace(/([`$\\])/g, '\\$1');

fixes.push(fixer.replaceText(expression, escapedValue));
} else if (expression.type === AST_NODE_TYPES.TemplateLiteral) {
// Note that some template literals get handled in the previous branch too.
// Remove the beginning and trailing backtick characters.
fixes.push(
fixer.removeRange([
expression.range[0],
expression.range[0] + 1,
]),
fixer.removeRange([
expression.range[1] - 1,
expression.range[1],
]),
);
}

return fixes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ ruleTester.run('no-useless-template-literals', rule, {
noFormat`
\`with windows \r new line\`;
`,

`
\`not a useless \${String.raw\`nested interpolation \${a}\`}\`;
`,
],

invalid: [
Expand Down Expand Up @@ -555,5 +559,67 @@ ruleTester.run('no-useless-template-literals', rule, {
},
],
},

{
code: "`use${'less'}`;",
output: '`useless`;',
errors: [
{
messageId: 'noUselessTemplateLiteral',
line: 1,
},
],
},

{
code: `
declare const nested: string, interpolation: string;
\`use\${\`less\${nested}\${interpolation}\`}\`;
`,
output: `
declare const nested: string, interpolation: string;
\`useless\${nested}\${interpolation}\`;
`,
errors: [
{
messageId: 'noUselessTemplateLiteral',
},
],
},

{
code: noFormat`
\`u\${
// hopefully this comment is not needed.
'se'
}\${
\`le\${ \`ss\` }\`
}\`;
`,
output: `
\`use\${
\`less\`
}\`;
`,
errors: [
{
messageId: 'noUselessTemplateLiteral',
line: 4,
},
{
messageId: 'noUselessTemplateLiteral',
line: 7,
column: 3,
endLine: 7,
},
{
messageId: 'noUselessTemplateLiteral',
line: 7,
column: 10,
endLine: 7,
},
],
},
],
});

0 comments on commit 8bdddbd

Please sign in to comment.