Created
October 27, 2021 11:52
-
-
Save bogas04/d27ec339ff48758525bb4ca3136367cb to your computer and use it in GitHub Desktop.
A babel plugin to replace all `cond && <Jsx />` to `cond ? <Jsx /> : null`
This file contains 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
/** | |
* A simple babel plugin that replaces all logical expressions used within JSX to use ternary operator | |
* ast explorer: https://astexplorer.net/#/gist/ce3b67aad0896abb10f89e8bf6805819/288e7e77857ae203296e6ee81b1235ff3f4e7b20 | |
*/ | |
module.exports = function (babel) { | |
const {types: t} = babel; | |
return { | |
name: 'ternary-jsx', // not required | |
visitor: { | |
JSXExpressionContainer(path, parent) { | |
if (path.parent.type === 'JSXAttribute') { | |
return; | |
} | |
const {type, operator, left, right} = path.node.expression; | |
let newExpression = null; | |
if (type === 'LogicalExpression' && operator === '&&') { | |
newExpression = t.ConditionalExpression(left, right, t.nullLiteral()); | |
} | |
if (type === 'LogicalExpression' && operator === '||') { | |
newExpression = t.LogicalExpression('??', left, right); | |
} | |
if (newExpression) { | |
path.replaceWith(t.JSXExpressionContainer(newExpression)); | |
} | |
}, | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Created a babel plugin to automatically fix this error in a codebase
steps to use
npm i -D @babel/cli
npx babel src -x ".tsx" --out-dir src --keep-file-extension
(update extensions as per your project)