Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [no-useless-template-literal] do not render escaped strings in autofixes #8688

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
12 changes: 10 additions & 2 deletions packages/eslint-plugin/src/rules/no-useless-template-literals.ts
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In addition to the comment, one thing though that I want to flag is that in the issue it was also intended that

`${'a'}`; 
// should autofix to 
`a`;
// rather than 
'a';

@kirkwaiblinger, Ohh, I missed that in the original issue!

I'm 50/50 on this!

though it's possible that that flew under the radar on the issue itself as well when it was marked accepting PRs.

Maybe..

Fixing to string literal vs template literal sounds a bit stylistic to me, I think it would be great to hear more opinions on this!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, agreed. I will say, at the time, I didn't realize it was just removing the wrapping template syntax, as opposed to overriding whatever the user had typed with one particular quote style. So my motivation for that change has softened a lot as well. It still feels a little surprising to me, but it does have a very justifiable internal logic as-is.

So unless someone comes in and has a strong opinion, I'd say, just leave it as-is :)

Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,16 @@ export default createRule<[], MessageId>({
if (isLiteral(expression)) {
const escapedValue =
auvred marked this conversation as resolved.
Show resolved Hide resolved
typeof expression.value === 'string'
? expression.raw.slice(1, -1).replace(/([`$])/g, '\\$1')
: String(expression.value).replace(/([`$\\])/g, '\\$1');
? // '1' -> 1
// '`' -> \`
// '${}' -> \${}
// '\\' -> \\
expression.raw.slice(1, -1).replace(/([`$])/g, '\\$1')
auvred marked this conversation as resolved.
Show resolved Hide resolved
: // 1 -> 1
// /`/ -> /\`/
// /${}/ -> /\${}/
// /\\/ -> /\\\\/
String(expression.value).replace(/([`$\\])/g, '\\$1');
auvred marked this conversation as resolved.
Show resolved Hide resolved

fixes.push(fixer.replaceText(expression, escapedValue));
} else if (isTemplateLiteral(expression)) {
Expand Down