@babel/plugin-proposal-do-expressions

Detail

The do { .. } expression executes a block (with one or many statements in it), and the final statement completion value inside the block becomes the completion value of the do expression.

from You Don't Know JS

It can be seen as a complex version of the ternary operator:

  1. let a = do {
  2. if(x > 10) {
  3. 'big';
  4. } else {
  5. 'small';
  6. }
  7. };
  8. // is equivalent to:
  9. let a = x > 10 ? 'big' : 'small';

This example is not the best usage because it is too simple and using a ternary operator is a better option but you can have a much more complex condition in the do { … } expression with several if … else chains:

  1. let x = 100;
  2. let y = 20;
  3. let a = do {
  4. if(x > 10) {
  5. if(y > 20) {
  6. 'big x, big y';
  7. } else {
  8. 'big x, small y';
  9. }
  10. } else {
  11. if(y > 10) {
  12. 'small x, big y';
  13. } else {
  14. 'small x, small y';
  15. }
  16. }
  17. };

Example

In JSX

One of the most useful usage of the do expression is inside JSX. If we want to conditionally display a component we usually have to call another function which would implement the condition and return the correct value, for example:

  1. const getColoredComponent = color => {
  2. if(color === 'blue') { return <BlueComponent/>; }
  3. if(color === 'red') { return <RedComponent/>; }
  4. if(color === 'green') { return <GreenComponent/>; }
  5. }
  6. const Component = props =>
  7. <div className='myComponent'>
  8. {getColoredComponent()}
  9. </div>
  10. ;

Using a do expression you can add logic inside JSX:

  1. const Component = props =>
  2. <div className='myComponent'>
  3. {do {
  4. if(color === 'blue') { <BlueComponent/>; }
  5. else if(color === 'red') { <RedComponent/>; }
  6. else if(color === 'green') { <GreenComponent/>; }
  7. }}
  8. </div>
  9. ;

Installation

  1. npm install --save-dev @babel/plugin-proposal-do-expressions

Usage

.babelrc

  1. {
  2. "plugins": ["@babel/plugin-proposal-do-expressions"]
  3. }

Via CLI

  1. babel --plugins @babel/plugin-proposal-do-expressions script.js

Via Node API

  1. require("@babel/core").transform("code", {
  2. plugins: ["@babel/plugin-proposal-do-expressions"]
  3. });

References