@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, Types & Grammar -> Chapter 5 -> Section Statement Completion Values

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") {
  3. return <BlueComponent />;
  4. }
  5. if (color === "red") {
  6. return <RedComponent />;
  7. }
  8. if (color === "green") {
  9. return <GreenComponent />;
  10. }
  11. };
  12. const Component = props => (
  13. <div className="myComponent">{getColoredComponent()}</div>
  14. );

Using a do expression you can add logic inside JSX:

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

Installation

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

Usage

  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").transformSync("code", {
  2. plugins: ["@babel/plugin-proposal-do-expressions"],
  3. });

References