React constant elements transformer

Treat React JSX elements as value types and hoist them to the highest scope.

Hoists element creation to the top level for subtrees that are fully static, which reduces call to React.createElement and the resulting allocations. More importantly, it tells React that the subtree hasn’t changed so React can completely skip it when reconciling.

This transform should be enabled only in production (e.g., just before minifying your code) because although it improves runtime performance, it makes warning messages more cryptic.

示例

输入

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

输出

const _ref = <hr className="hr" />;

const Hr = () => {
  return _ref;
};

Deopts

  • 展开运算符

    <div {...foobar} />
    
  • Refs

    <div ref="foobar" />
    <div ref={node => this.node = node} />
    

安装

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

用法

通过 .babelrc(推荐)

.babelrc

{
  "plugins": ["transform-react-constant-elements"]
}

通过 CLI

babel --plugins transform-react-constant-elements script.js

通过 Node API

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

参考