@babel/plugin-transform-react-inline-elements
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
注意
当与 @babel/plugin-transform-runtime 一同使用时,polyfill(默认包含 Symbol)会被限定在特定作用域内以避免污染全局作用域。这将导致与 React 配合使用时出现问题,因为 React 无法访问该 polyfill,从而在旧版浏览器中导致应用运行失败。
即使指定了 ['@babel/plugin-transform-runtime', { helpers: true, polyfill: false }] 配置,仍可能发生故障,因为 helpers 是预编译的。
这种情况下,我们建议在应用入口点导入/引入 @babel/polyfill,并使用 @babel/preset-env 的 useBuiltIns 选项来仅包含目标环境所需的 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",
* });
*/
优化降级
JavaScript
// The plugin will still use React.createElement when `ref` or `object rest spread` is used
<Foo ref="bar" />
<Foo {...bar} />
安装
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-react-inline-elements
yarn add --dev @babel/plugin-transform-react-inline-elements
pnpm add --save-dev @babel/plugin-transform-react-inline-elements
bun add --dev @babel/plugin-transform-react-inline-elements
用法
通过配置文件(推荐)
babel.config.json
{
"plugins": ["@babel/plugin-transform-react-inline-elements"]
}
通过命令行
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"],
});