Skip to main content

@babel/plugin-transform-react-constant-elements

这个插件可以通过将 React 元素提升到尽可能高的作用域,加快调和速度并减少垃圾回收压力,从而避免多次不必要的重新实例化。

🌐 This plugin can speed up reconciliation and reduce garbage collection pressure by hoisting React elements to the highest possible scope, preventing multiple unnecessary reinstantiations.

示例​

🌐 Example

在

JSX
const Hr = () => {
return <hr className="hr" />;
};

const WithChildren = (props) => {
return <div className={props.className}>
<hr />
</div>;
}

出

JSX
var _hr, _hr2;

const Hr = () => {
return _hr || (_hr = <hr className="hr" />);
};

const WithChildren = (props) => {
return <div className={props.className}>
{_hr2 || (_hr2 = <hr />)}
</div>;
}

取消优化

  • 扩展运算符

    JSX
    <div {...foobar} />
  • 参考

    JSX
    <div ref="foobar" />
    <div ref={node => this.node = node} />
  • 可变属性

JavaScript
<div style={{ width: 100 }} />

安装​

🌐 Installation

npm install --save-dev @babel/plugin-transform-react-constant-elements

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

babel.config.json
{
"plugins": ["@babel/plugin-transform-react-constant-elements"]
}

选项​

🌐 Options

allowMutablePropsOnTags​

Array<string>,默认值为 []

如果你在使用某个特定的库(比如 react-intl)并使用对象属性,而且你确定元素不会修改它自己的 props,那么你可以允许对象被特定的元素使用。

🌐 If you are using a particular library (like react-intl) that uses object properties, and you are sure that the element won't modify its own props, you can permit objects to be allowed for specific elements.

这会跳过 Mutable Properties 的去优化。

🌐 This will skip the Mutable Properties deopt.

babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-react-constant-elements",
{ "allowMutablePropsOnTags": ["FormattedMessage"] }
]
]
}
tip

你可以在这里了解更多关于配置插件选项的内容

通过 CLI​

🌐 Via CLI

Shell
babel --plugins @babel/plugin-transform-react-constant-elements script.js

通过 Node API​

🌐 Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-react-constant-elements"],
});

参考​

🌐 References