From 35ee14ab3f3d5c54f846d4a35cd2893d2cc06a6c Mon Sep 17 00:00:00 2001 From: Nitin Kumar Date: Thu, 28 Oct 2021 17:41:03 -0700 Subject: [PATCH] fix: do not concatenate string literals --- lib/rules/prefer-template.js | 6 +++--- tests/lib/rules/prefer-template.js | 24 ++++++++++++++++++------ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/lib/rules/prefer-template.js b/lib/rules/prefer-template.js index fbd9b5ca339..65826fd2bf2 100644 --- a/lib/rules/prefer-template.js +++ b/lib/rules/prefer-template.js @@ -202,11 +202,11 @@ module.exports = { } if (isConcatenation(currentNode) && !hasIdentifierReference(currentNode)) { + const nodeTexts = sourceCode.getText(currentNode).split("+"); - // As there are no varibales used in this concatenation, we can sipmly calculate the concatenated string - const concatenatedText = sourceCode.getText(currentNode).split("+").map(e => e.trim().slice(1, -1)).join(""); + nodeTexts[nodeTexts.length - 1] = ` \`${nodeTexts[nodeTexts.length - 1].trim().slice(1)}`; - return `\`${concatenatedText}\``; + return nodeTexts.join("+"); } if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) { diff --git a/tests/lib/rules/prefer-template.js b/tests/lib/rules/prefer-template.js index ffb0cda86a9..a237183bc3d 100644 --- a/tests/lib/rules/prefer-template.js +++ b/tests/lib/rules/prefer-template.js @@ -227,25 +227,37 @@ ruleTester.run("prefer-template", rule, { // https://github.com/eslint/eslint/issues/15083 { - code: "\"Hello \" + \"world \" + test", - output: "`Hello world ${ test}`", + code: "'a' + 'b' + foo", + output: "'a' + `b${ foo}`", + errors + }, + { + code: "'a' + 'b' + foo + 'c' + 'd'", + output: "'a' + `b${ foo }c` + `d`", errors }, { code: "var foo = \"Hello \" + \"world \" + \"another \" + test", - output: "var foo = `Hello world another ${ test}`", + output: "var foo = \"Hello \" + \"world \" + `another ${ test}`", + errors + }, + { + code: "'Hello ' + '\"world\" ' + test", + output: "'Hello ' + `\"world\" ${ test}`", errors }, { code: "\"Hello \" + \"'world' \" + test", - output: "`Hello 'world' ${ test}`", + output: "\"Hello \" + `'world' ${ test}`", errors }, { code: `"default-src 'self' https://*.google.com;" + "frame-ancestors 'none';" - + "report-to " + test + ";"`, - output: "`default-src 'self' https://*.google.com;frame-ancestors 'none';report-to ${ test };`", + + "report-to " + foo + ";"`, + output: `"default-src 'self' https://*.google.com;" + + "frame-ancestors 'none';" + + \`report-to \${ foo };\``, errors } ]