0%

How to replace && with ternary operators

In React Native, logical AND may cause crash as below.

Conditional rendering in React Native may crash your app

This babel plugin here can replace all logical AND with ternary operators, with a little more configuration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// .babelrc.js
module.exports = function (api) {
api.cache(true);

const presets = [];
const plugins = [
'./ternary-jsx.js',
// this two plugins below only parse but not transform code
['@babel/plugin-syntax-decorators', { decoratorsBeforeExport: true }],
['@babel/plugin-syntax-class-properties', { loose: true }],
];

return {
parserOpts: {
plugins: ['jsx', 'typescript'],
},
presets,
plugins,
generatorOpts: {
retainLines: true,
compact: false,
minified: false,
concise: false,
},
};
};

However, Babel will lose some code formatting in the process, as it works based on the AST..