UNPKG

2.73 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to check spacing between template tags and their literals
3 * @author Jonathan Wilsson
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13 meta: {
14 docs: {
15 description: "require or disallow spacing between template tags and their literals",
16 category: "Stylistic Issues",
17 recommended: false,
18 url: "https://eslint.org/docs/rules/template-tag-spacing"
19 },
20
21 fixable: "whitespace",
22
23 schema: [
24 { enum: ["always", "never"] }
25 ]
26 },
27
28 create(context) {
29 const never = context.options[0] !== "always";
30 const sourceCode = context.getSourceCode();
31
32 /**
33 * Check if a space is present between a template tag and its literal
34 * @param {ASTNode} node node to evaluate
35 * @returns {void}
36 * @private
37 */
38 function checkSpacing(node) {
39 const tagToken = sourceCode.getTokenBefore(node.quasi);
40 const literalToken = sourceCode.getFirstToken(node.quasi);
41 const hasWhitespace = sourceCode.isSpaceBetweenTokens(tagToken, literalToken);
42
43 if (never && hasWhitespace) {
44 context.report({
45 node,
46 loc: tagToken.loc.start,
47 message: "Unexpected space between template tag and template literal.",
48 fix(fixer) {
49 const comments = sourceCode.getCommentsBefore(node.quasi);
50
51 // Don't fix anything if there's a single line comment after the template tag
52 if (comments.some(comment => comment.type === "Line")) {
53 return null;
54 }
55
56 return fixer.replaceTextRange(
57 [tagToken.range[1], literalToken.range[0]],
58 comments.reduce((text, comment) => text + sourceCode.getText(comment), "")
59 );
60 }
61 });
62 } else if (!never && !hasWhitespace) {
63 context.report({
64 node,
65 loc: tagToken.loc.start,
66 message: "Missing space between template tag and template literal.",
67 fix(fixer) {
68 return fixer.insertTextAfter(tagToken, " ");
69 }
70 });
71 }
72 }
73
74 return {
75 TaggedTemplateExpression: checkSpacing
76 };
77 }
78};