跳至主要內容

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

注意

@babel/plugin-transform-runtime 一起使用時,polyfill(預設包含 Symbol)特別限定範圍,不會污染全域範圍。這會中斷與 React 的使用,因為它無法存取該 polyfill,而且會導致應用程式在舊版瀏覽器中失敗。

即使指定了 ['@babel/plugin-transform-runtime', { helpers: true, polyfill: false }],它仍可能中斷,因為 helpers 是預先編譯的。

在這種情況下,我們建議在應用程式的進入點匯入/需要 @babel/polyfill,並使用 @babel/preset-envuseBuiltIns 選項,僅包含目標所需的 polyfill。或者,您也可以自行匯入/需要 core-js/modules/es6.symbol

此轉換 僅應在生產環境中啟用(例如,在縮小程式碼之前),因為儘管它改善了執行時間效能,但它會使警告訊息更難懂,並略過開發模式中發生的重要檢查,包括 propTypes。

範例

JavaScript
<Baz foo="bar" key="1" />

輸出

JavaScript
babelHelpers.jsx(
Baz,
{
foo: "bar",
},
"1"
);

/**
* Instead of
*
* React.createElement(Baz, {
* foo: "bar",
* key: "1",
* });
*/

Deopt

JavaScript
// The plugin will still use React.createElement when `ref` or `object rest spread` is used
<Foo ref="bar" />
<Foo {...bar} />

安裝

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

用法

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

透過 CLI

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

透過 Node API

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

參考