Skip to content

Commit

Permalink
string-content: Ignore some TaggedTemplateExpression (#585)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
fisker and sindresorhus committed Mar 11, 2020
1 parent e7e49ec commit 92f3f3d
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 2 deletions.
7 changes: 7 additions & 0 deletions docs/rules/string-content.md
Expand Up @@ -6,6 +6,13 @@ This rule is fixable.

*It only reports one pattern per AST node at the time.*

This rule ignores the following tagged template literals as they're known to contain code:

- ``gql`…` ``
- ``html`…` ``
- ``svg`…` ``
- ``styled.*`…` ``

## Fail

```js
Expand Down
36 changes: 35 additions & 1 deletion rules/string-content.js
Expand Up @@ -8,6 +8,40 @@ const defaultPatterns = {
'\'': '’'
};

const ignoredIdentifier = new Set([
'gql',
'html',
'svg'
]);

const ignoredMemberExpressionObject = new Set([
'styled'
]);

const isIgnoredTag = node => {
if (!node.parent || !node.parent.parent || !node.parent.parent.tag) {
return false;
}

const {tag} = node.parent.parent;

if (tag.type === 'Identifier' && ignoredIdentifier.has(tag.name)) {
return true;
}

if (tag.type === 'MemberExpression') {
const {object} = tag;
if (
object.type === 'Identifier' &&
ignoredMemberExpressionObject.has(object.name)
) {
return true;
}
}

return false;
};

const defaultMessage = 'Prefer `{{suggest}}` over `{{match}}`.';

function getReplacements(patterns) {
Expand Down Expand Up @@ -53,7 +87,7 @@ const create = context => {
if (typeof string !== 'string') {
return;
}
} else {
} else if (!isIgnoredTag(node)) {
string = node.value.raw;
}

Expand Down
29 changes: 28 additions & 1 deletion test/string-content.js
Expand Up @@ -41,7 +41,28 @@ ruleTester.run('string-content', rule, {
// `TemplateLiteral`
'const foo = `🦄`',
// Should not escape
'const foo = `\\`\\${1}`'
'const foo = `\\`\\${1}`',
// Ignored
`
const foo = gql\`{
field(input: '...')
}\`;
`,
`
const foo = styled.div\`
background: url('...')
\`;
`,
`
const foo = html\`
<div class='test'>...</div>
\`;
`,
`
const foo = svg\`
<svg xmlns="http://www.w3.org/2000/svg"><path fill='#00CD9F'/></svg>
\`;
`
/* eslint-enable no-template-curly-in-string */
],
invalid: [
Expand Down Expand Up @@ -198,6 +219,12 @@ ruleTester.run('string-content', rule, {
output: 'const foo = `\\\\\\${bar}`',
options: [{patterns: {foo: '{bar}'}}],
errors: createError('foo', '{bar}')
},
// Not ignored tag
{
code: 'const foo = notIgnoredTag`\'`',
output: 'const foo = notIgnoredTag`’`',
errors: createError('\'', '’')
}
/* eslint-enable no-template-curly-in-string */
]
Expand Down

0 comments on commit 92f3f3d

Please sign in to comment.