[go: up one dir, main page]

Skip to content

Commit

Permalink
feat(eslint-plugin): [no-useless-template-literals] add fix suggestio…
Browse files Browse the repository at this point in the history
…ns (#8065)

* feat(eslint-plugin): [no-useless-template-literals] add fix suggestions

* change message

* add quasis to cspell

* add some test cases

* use fix instead of suggestion
  • Loading branch information
StyleShit authored Jan 9, 2024
1 parent 8ca5e5e commit c3767ed
Show file tree
Hide file tree
Showing 3 changed files with 244 additions and 14 deletions.
1 change: 1 addition & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
"preact",
"Premade",
"prettier's",
"quasis",
"Quickstart",
"recurse",
"redeclaration",
Expand Down
55 changes: 53 additions & 2 deletions packages/eslint-plugin/src/rules/no-useless-template-literals.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TSESTree } from '@typescript-eslint/utils';
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as ts from 'typescript';

Expand All @@ -15,7 +15,8 @@ type MessageId = 'noUselessTemplateLiteral';
export default createRule<[], MessageId>({
name: 'no-useless-template-literals',
meta: {
type: 'problem',
fixable: 'code',
type: 'suggestion',
docs: {
description: 'Disallow unnecessary template literals',
recommended: 'strict',
Expand Down Expand Up @@ -68,6 +69,22 @@ export default createRule<[], MessageId>({
context.report({
node: node.expressions[0],
messageId: 'noUselessTemplateLiteral',
fix(fixer): TSESLint.RuleFix[] {
const [prevQuasi, nextQuasi] = node.quasis;

// Remove the quasis and backticks.
return [
fixer.removeRange([
prevQuasi.range[1] - 3,
node.expressions[0].range[0],
]),

fixer.removeRange([
node.expressions[0].range[1],
nextQuasi.range[0] + 2,
]),
];
},
});

return;
Expand All @@ -83,6 +100,40 @@ export default createRule<[], MessageId>({
context.report({
node: expression,
messageId: 'noUselessTemplateLiteral',
fix(fixer): TSESLint.RuleFix[] {
const index = node.expressions.indexOf(expression);
const prevQuasi = node.quasis[index];
const nextQuasi = node.quasis[index + 1];

// Remove the quasis' parts that are related to the current expression.
const fixes = [
fixer.removeRange([
prevQuasi.range[1] - 2,
expression.range[0],
]),

fixer.removeRange([
expression.range[1],
nextQuasi.range[0] + 1,
]),
];

// Remove quotes for string literals (i.e. `'a'` will become `a`).
const isStringLiteral =
isUnderlyingTypeString(expression) &&
expression.type === AST_NODE_TYPES.Literal;

if (isStringLiteral) {
const escapedValue = expression.value.replace(
/([`$\\])/g,
'\\$1',
);

fixes.push(fixer.replaceText(expression, escapedValue));
}

return fixes;
},
});
});
},
Expand Down
Loading

0 comments on commit c3767ed

Please sign in to comment.