UNPKG

1.14 kBJavaScriptView Raw
1const {docsUrl} = require('../utilities');
2
3module.exports = {
4 meta: {
5 docs: {
6 description:
7 'Disallow useless wrapping elements in favour of fragment shorthand in JSX',
8 category: 'Best Practices',
9 recommended: false,
10 uri: docsUrl('jsx-prefer-fragment-wrappers'),
11 },
12 },
13
14 create(context) {
15 return {
16 JSXElement(node) {
17 if (
18 isAcceptedTagName(node) ||
19 hasOneOrNoChildren(node) ||
20 hasAttributes(node)
21 ) {
22 return;
23 }
24
25 const {name} = node.openingElement.name;
26
27 context.report({
28 node,
29 message: 'replace wrapping {{name}} with fragment shorthand',
30 data: {name},
31 });
32 },
33 };
34 },
35};
36
37function isAcceptedTagName({openingElement: {name}}) {
38 return !['div', 'span'].some((tagName) => tagName === name.name);
39}
40
41function hasOneOrNoChildren({children}) {
42 const childNodes = children.filter((child) => child.type !== 'Literal');
43 return childNodes.length < 2;
44}
45
46function hasAttributes({openingElement: {attributes}}) {
47 return attributes && attributes.length !== 0;
48}