babel-preset-react中useBuiltIns配置的用途及具体含义咨询
useBuiltIns in babel-preset-react I get it—you’re comfortable with how useBuiltIns works in babel-preset-env, but the same config in babel-preset-react has you scratching your head. Let’s break down that official description and make it concrete with examples.
First, quick context: babel-preset-react bundles several plugins that handle React code transformations (like converting JSX to React.createElement, adding display names, etc.). Some of these plugins rely on JavaScript built-in features (think Object.assign, Array.prototype.includes, etc.) to do their work. The useBuiltIns config controls how these plugins access those features.
Let’s break down the two possible values:
When useBuiltIns: false (default)
In this mode, the preset’s plugins will include their own polyfilled versions of the required built-ins instead of relying on the browser’s native implementation.
For example, when merging JSX props with the spread operator (<MyComponent {...props} />), Babel won’t use the native Object.assign. Instead, it’ll inject a custom implementation of the assign logic directly into your code. This ensures compatibility with older browsers that don’t support Object.assign, but it adds extra code to your bundle—since that polyfill gets included wherever it’s needed.
When useBuiltIns: true
Flip this to true, and the plugins will directly use the browser’s native built-in features instead of rolling their own.
Using the same JSX spread example: instead of injecting a custom assign function, Babel will generate code that calls the native Object.assign directly. This keeps your bundle smaller, but it requires that all your target browsers already support the built-ins in question.
A side-by-side code example
Let’s say you write this JSX:
<Button label="Click me" {...buttonProps} />
With useBuiltIns: false, the transformed code looks like this (simplified):
// Babel's custom polyfill for Object.assign var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; React.createElement(Button, _extends({ label: "Click me" }, buttonProps));
With useBuiltIns: true, it’s much cleaner:
React.createElement(Button, Object.assign({ label: "Click me" }, buttonProps));
Key takeaway
This config is all about tradeoffs:
- Use
falseif you need to support older browsers that lack the required built-ins—Babel’s polyfills will ensure your code works everywhere, at the cost of a slightly larger bundle. - Use
trueif you’re already handling polyfills viababel-preset-envor another tool, and your target browsers all support the necessary built-ins—this cuts down on redundant code and keeps your bundle lean.
内容的提问来源于stack exchange,提问作者makkBit

