Skip to main content

@babel/plugin-proposal-do-expressions

详情​

🌐 Detail

do { .. } 表达式会执行一个代码块(里面可以有一个或多个语句),而代码块中最后一个语句的完成值会成为整个 do 表达式的完成值。

来自《你不知道的 JS》(https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/types%20%26%20grammar/ch5.md#statement-completion-values),类型与语法 -> 第5章 -> 语句完成值部分

🌐 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:

JavaScript
let a = do {
if (x > 10) {
("big");
} else {
("small");
}
};
// is equivalent to:
let a = x > 10 ? "big" : "small";

这个例子不是最好的用法,因为它太简单了,使用三元运算符会是更好的选择,但你可以在 do { ... } 表达式中有一个更复杂的条件,并且包含多个 if ... else 链:

🌐 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:

JavaScript
let x = 100;
let y = 20;

let a = do {
if (x > 10) {
if (y > 20) {
("big x, big y");
} else {
("big x, small y");
}
} else {
if (y > 10) {
("small x, big y");
} else {
("small x, small y");
}
}
};

示例​

🌐 Example

在 JSX 中​

🌐 In JSX

do 表达式最有用的用法之一是在 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:

JavaScript
const getColoredComponent = color => {
if (color === "blue") {
return <BlueComponent />;
}
if (color === "red") {
return <RedComponent />;
}
if (color === "green") {
return <GreenComponent />;
}
};

const Component = props => (
<div className="myComponent">{getColoredComponent()}</div>
);

使用 do 表达式,你可以在 JSX 中添加逻辑:

🌐 Using a do expression you can add logic inside JSX:

JavaScript
const Component = props => (
<div className="myComponent">
{do {
if (color === "blue") {
<BlueComponent />;
} else if (color === "red") {
<RedComponent />;
} else if (color === "green") {
<GreenComponent />;
}
}}
</div>
);

安装​

🌐 Installation

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

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

babel.config.json
{
"plugins": ["@babel/plugin-proposal-do-expressions"]
}

通过 CLI​

🌐 Via CLI

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

通过 Node API​

🌐 Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-do-expressions"],
});

参考​

🌐 References