@babel/plugin-transform-react-inline-elements
注意
🌐 Note
当与 @babel/plugin-transform-runtime 一起使用时,polyfills(默认包括 Symbol)会被特意限制范围,避免污染全局作用域。这会影响 React 的使用,因为它无法访问那个 polyfill,从而导致你的应用在老旧浏览器中出错。
🌐 When used alongside @babel/plugin-transform-runtime, polyfills (by default including Symbol) are specifically scoped to not pollute the global scope. This breaks usage with React, as it won't have access to that polyfill and will cause your application to fail in legacy browsers.
即使指定了 ['@babel/plugin-transform-runtime', { helpers: true, polyfill: false }],它仍然可能会出问题,因为 helpers 是预先编译好的。
🌐 Even if ['@babel/plugin-transform-runtime', { helpers: true, polyfill: false }] is specified, it might still break, since helpers come precompiled.
在这种情况下,我们建议在你的应用入口点导入/引入 @babel/polyfill,并使用带有 useBuiltIns 选项的 @babel/preset-env 来只包含你的目标所需的 polyfill。或者,你也可以单独导入/引入 core-js/modules/es6.symbol。
🌐 In this case, we recommend importing/requiring @babel/polyfill in the entry point of your application and using @babel/preset-env with the useBuiltIns option to only include the polyfills your targets need. Alternatively, you can also import/require core-js/modules/es6.symbol by itself.
这个转换应该只在生产环境中启用(例如,就在压缩代码之前),因为虽然它能提升运行时性能,但会让警告信息更难懂,并且跳过在开发模式下进行的重要检查,包括 propTypes。
🌐 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 and skips important checks that happen in development mode, including propTypes.
示例
🌐 Example
在
<Baz foo="bar" key="1" />
出
babelHelpers.jsx(
Baz,
{
foo: "bar",
},
"1"
);
/**
* Instead of
*
* React.createElement(Baz, {
* foo: "bar",
* key: "1",
* });
*/
去优化
// The plugin will still use React.createElement when `ref` or `object rest spread` is used
<Foo ref="bar" />
<Foo {...bar} />
安装
🌐 Installation
- 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
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-transform-react-inline-elements"]
}
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-react-inline-elements script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-react-inline-elements"],
});
参考
🌐 References