Skip to content

prefer-string-raw: Add support for template literals #2691

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

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/rules/prefer-string-raw.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ const file = "C:\\windows\\style\\path\\to\\file.js";
const regexp = new RegExp('foo\\.bar');
```

```js
const file = `C:\\windows\\temp\\myapp-${process.pid}.log`;
```

## Pass

```js
Expand All @@ -28,3 +32,7 @@ const file = String.raw`C:\windows\style\path\to\file.js`;
```js
const regexp = new RegExp(String.raw`foo\.bar`);
```

```js
const file = String.raw`C:\windows\temp\myapp-${process.pid}.log`;
```
42 changes: 33 additions & 9 deletions rules/prefer-string-raw.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {isStringLiteral, isDirective} from './ast/index.js';
import {fixSpaceAroundKeyword} from './fix/index.js';
import {fixSpaceAroundKeyword, replaceTemplateElement} from './fix/index.js';

const MESSAGE_ID = 'prefer-string-raw';
const messages = {
Expand All @@ -8,12 +8,8 @@ const messages = {

const BACKSLASH = '\\';

function unescapeBackslash(raw) {
const quote = raw.charAt(0);

return raw
.slice(1, -1)
.replaceAll(new RegExp(String.raw`\\(?<escapedCharacter>[\\${quote}])`, 'g'), '$<escapedCharacter>');
function unescapeBackslash(text, quote = '') {
return text.replaceAll(new RegExp(String.raw`\\(?<escapedCharacter>[\\${quote}])`, 'g'), '$<escapedCharacter>');
}

/** @param {import('eslint').Rule.RuleContext} context */
Expand Down Expand Up @@ -50,7 +46,7 @@ const create = context => {
return;
}

const unescaped = unescapeBackslash(raw);
const unescaped = unescapeBackslash(raw.slice(1, -1), raw.charAt(0));
if (unescaped !== node.value) {
return;
}
Expand All @@ -59,8 +55,36 @@ const create = context => {
node,
messageId: MESSAGE_ID,
* fix(fixer) {
yield fixer.replaceText(node, `String.raw\`${unescaped}\``);
yield * fixSpaceAroundKeyword(fixer, node, sourceCode);
yield fixer.replaceText(node, `String.raw\`${unescaped}\``);
},
};
});

context.on('TemplateLiteral', node => {
if (
(node.parent.type === 'TaggedTemplateExpression' && node.parent.quasi === node)
|| node.quasis.every(({value: {cooked, raw}}) => cooked === raw)
|| node.quasis.some(({value: {cooked, raw}}) => cooked.at(-1) === BACKSLASH || unescapeBackslash(raw) !== cooked)
) {
return;
}

return {
node,
messageId: MESSAGE_ID,
* fix(fixer) {
yield * fixSpaceAroundKeyword(fixer, node, context.sourceCode);
yield fixer.insertTextBefore(node, 'String.raw');

for (const quasis of node.quasis) {
const {cooked, raw} = quasis.value;
if (cooked === raw) {
continue;
}

yield replaceTemplateElement(fixer, quasis, cooked);
}
},
};
});
Expand Down
4 changes: 2 additions & 2 deletions rules/prefer-string-replace-all.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ function getPatternReplacement(node) {
return String.raw`\t`;
}

return `\\u{${codePoint.toString(16)}}`;
return String.raw`\u{${codePoint.toString(16)}}`;
}

if (kind === 'octal') {
return `\\u{${codePoint.toString(16)}}`;
return String.raw`\u{${codePoint.toString(16)}}`;
}

let character = raw;
Expand Down
52 changes: 51 additions & 1 deletion test/prefer-string-raw.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
/* eslint-disable no-template-curly-in-string */
import outdent from 'outdent';
import {getTester} from './utils/test.js';

const {test} = getTester(import.meta);

// String literal to `String.raw`
test.snapshot({
valid: [
String.raw`a = '\''`,
Expand All @@ -18,7 +20,6 @@ test.snapshot({
`,
String.raw`a = 'a\\b\u{51}c'`,
'a = "a\\\\b`"',
// eslint-disable-next-line no-template-curly-in-string
'a = "a\\\\b${foo}"',
{
code: String.raw`<Component attribute="a\\b" />`,
Expand Down Expand Up @@ -47,6 +48,55 @@ test.snapshot({
],
});

// `TemplateLiteral` to `String.raw`
test.snapshot({
valid: [
// No backslash
'a = `a`',
'a = `${foo}`',
'a = `a${100}b`',

// Escaped characters other than backslash
'a = `a\\t${foo.bar}b\\\\c`', // \t
'a = `${foo}\\\\a${bar}\\``', // \`
'a = `a\\${`', // \$
'a = `a$\\{`', // \{
'a = `${a}\\\'${b}\\\\`', // \'
'a = `\\"a\\\\b`', // \"

// Ending with backslash
'a = `\\\\a${foo}b\\\\${foo}`',

// Tagged template expression
'a = String.raw`a\\\\b`',

// Slash before newline (spread into multiple lines)
outdent`
a = \`\\\\a \\
b\`
`,
],
invalid: [
'a = `a\\\\b`',
'function a() {return`a\\\\b${foo}cd`}',
'a = {[`a\\\\b${foo}cd${foo.bar}e\\\\f`]: b}',
'a = `a${foo}${foo.bar}b\\\\c`',
'a = `a\\\\b${"c\\\\d"}e`',
outdent`
a = \`\\\\a
b\`
`,
outdent`
a = \`\\\\a\${foo}
b\${bar}c
d\\\\\\\\e\`
`,
'a = `a\\\\b${ foo /* bar */}c\\\\d`',
'a = `a\\\\b${ foo + bar }`',
'a = `${ foo .bar }a\\\\b`',
],
});

test.typescript({
valid: [
outdent`
Expand Down
Loading
Loading