@babel/plugin-transform-destructuring
这个插件包含在 @babel/preset-env 中
示例
🌐 Examples
在
let { x, y } = obj;
let [a, b, ...rest] = arr;
出
function _toArray(arr) { ... }
let _obj = obj,
x = _obj.x,
y = _obj.y;
let _arr = arr,
_arr2 = _toArray(_arr),
a = _arr2[0],
b = _arr2[1],
rest = _arr2.slice(2);
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-destructuring
yarn add --dev @babel/plugin-transform-destructuring
pnpm add --save-dev @babel/plugin-transform-destructuring
bun add --dev @babel/plugin-transform-destructuring
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-transform-destructuring"]
}
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-destructuring script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-destructuring"],
});
选项
🌐 Options
loose
boolean,默认值为 false。
启用这个选项将假设你想要解构的是一个数组,并且不会在其他可迭代对象上使用 Array.from。
🌐 Enabling this option will assume that what you want to destructure is an array and won't use Array.from on other iterables.
考虑迁移到顶层 iterableIsArray 假设。
{
"assumptions": {
"iterableIsArray": true
}
}
useBuiltIns
boolean,默认值为 false。
启用此选项将直接使用 Object.assign,而不是 Babel 的 extends 辅助工具。
🌐 Enabling this option will use Object.assign directly instead of the Babel's extends helper.
示例
🌐 Example
.babelrc
{
"plugins": [
["@babel/plugin-transform-destructuring", { "useBuiltIns": true }]
]
}
在
var { ...x } = z;
出
var _z = z,
x = Object.assign({}, _z);
你可以在这里了解更多关于配置插件选项的内容
allowArrayLike
boolean,默认值为 false
已添加于:v7.10.0
🌐 Added in: v7.10.0
此选项允许使用数组解构语法来解构类似数组的对象。
🌐 This option allows destructuring array-like objects using the array destructuring syntax.
类数组对象是一个具有 length 属性的对象:例如 { 0: "a", 1: "b", length: 2 }。注意,像真正的数组一样,类数组对象也可以有“空洞”:{ 1: "a", length: 3 } 等同于 [ (hole), "a", (hole) ]。
🌐 An array-like object is an object with a length property: for example, { 0: "a", 1: "b", length: 2 }. Note that, like real arrays, array-like objects can have "holes": { 1: "a", length: 3 } is equivalent to [ (hole), "a", (hole) ].
虽然将类数组对象解构为数组的方式并不符合规范,但在现代浏览器中,很多对象在支持 Symbol.iterator 的情况下会是可迭代对象。一些显著的例子是 DOM 集合,比如 document.querySelectorAll("img.big"),它们是使用这个选项的主要场景。
🌐 While it is not spec-compliant to destructure array-like objects as if they were arrays, there are many objects that would be iterables in modern browsers with Symbol.iterator support. Some notable examples are the DOM collections, like document.querySelectorAll("img.big"), which are the main use case for this option.
请注意,即使禁用了这个选项,Babel 在旧引擎中仍然允许解构 arguments,因为它在 ECMAScript 规范中被定义为 可迭代的。
🌐 Please note that Babel allows destructuring arguments in old engines even if this option is disabled, because it's defined as iterable in the ECMAScript specification.
考虑迁移到顶层 arrayLikeIsIterable 假设。
{
"assumptions": {
"arrayLikeIsIterable": true
}
}
参考
🌐 References