@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
在
const Hr = () => {
return <hr className="hr" />;
};
const WithChildren = (props) => {
return <div className={props.className}>
<hr />
</div>;
}
出
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} /> -
可变属性
<div style={{ width: 100 }} />
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-react-constant-elements
yarn add --dev @babel/plugin-transform-react-constant-elements
pnpm add --save-dev @babel/plugin-transform-react-constant-elements
bun add --dev @babel/plugin-transform-react-constant-elements
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
{
"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.
{
"plugins": [
[
"@babel/plugin-transform-react-constant-elements",
{ "allowMutablePropsOnTags": ["FormattedMessage"] }
]
]
}
你可以在这里了解更多关于配置插件选项的内容
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-react-constant-elements script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-react-constant-elements"],
});
参考
🌐 References