Skip to content

Instantly share code, notes, and snippets.

@bogas04
Created October 27, 2021 11:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bogas04/d27ec339ff48758525bb4ca3136367cb to your computer and use it in GitHub Desktop.
Save bogas04/d27ec339ff48758525bb4ca3136367cb to your computer and use it in GitHub Desktop.
A babel plugin to replace all `cond && <Jsx />` to `cond ? <Jsx /> : null`
/**
* 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));
}
},
},
};
};
@bogas04
Copy link
Author

bogas04 commented Oct 27, 2021

Created a babel plugin to automatically fix this error in a codebase

steps to use

  • download the file
  • npm i -D @babel/cli
  • update babel config to include local plugin
module.exports = function (api) {
    api.cache(true);

    const presets = [];
    const plugins = ['./ternary-jsx.js'];

    return {
        parserOpts: {
            plugins: ['jsx', 'typescript'],
        },
        retainLines: true,
        presets,
        plugins,
    };
};
  • npx babel src -x ".tsx" --out-dir src --keep-file-extension (update extensions as per your project)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment