Created
October 28, 2017 06:37
-
-
Save Sparragus/dc0348f23459b5e402df723397ce1f7f to your computer and use it in GitHub Desktop.
Eslint plugin with a rule that enforces blank lines between sibling JSX elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const JSXELEMENT_CHILDREN = [ | |
'JSXText', | |
'JSXExpressionContainer', | |
'JSXSpreadChild', | |
'JSXElement', | |
'JSXFragment' | |
] | |
const isJSXElementChildrenType = x => x && JSXELEMENT_CHILDREN.includes(x.type) | |
module.exports = { | |
rules: { | |
'too-few-lines-between-jsx-elements': { | |
create: function(context) { | |
return { | |
JSXElement(node) { | |
node.children.forEach((child, index, children) => { | |
if (child.type === 'Literal') { | |
const prevChild = children[index - 1] | |
const nextChild = children[index + 1] | |
const isBetweenJSXElements = [prevChild, nextChild].every(isJSXElementChildrenType) | |
if (isBetweenJSXElements) { | |
const valueWithoutTabsAndSpaces = child.value.replace(/(\t| )/g, '') | |
const hasTooFewLinesBetween = /^\n{1}$/.test(valueWithoutTabsAndSpaces) | |
if (hasTooFewLinesBetween) { | |
context.report({ | |
node: child, | |
message: 'Too few lines between JSX elements', | |
fix: function(fixer) { | |
return fixer.insertTextAfter(child, '\n') | |
} | |
}) | |
} | |
} | |
} | |
}) | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AST explorer: http://astexplorer.net/#/gist/0cfc0bd890635fe7815bcd79fc32bd48/dcd48c8f667ac692f6c14806055c7001714ea53e