object rest spread useBuiltIns option (#4491)

* feat(transform-object-rest-spread): add polyfill=false option to avoid extends helper

* object-rest-spread: add useBuiltIns option

* add test for invalid option
This commit is contained in:
Henry Zhu 2016-09-09 18:38:50 -04:00 committed by GitHub
parent 3d93a2ab9c
commit d2d34ba8e7
7 changed files with 48 additions and 1 deletions

View File

@ -2,6 +2,15 @@
Compile object rest and spread to ES5
```js
// source
z = { x, ...y };
// compiled
_extends = Object.assign || function(target) { ... }
z = _extends({ x }, y);
```
## Installation
```sh
@ -20,6 +29,25 @@ $ npm install babel-plugin-transform-object-rest-spread
}
```
## Options
This plugin will use babel's `extends` helper, which will polyfill `Object.assign` by default.
* `useBuiltIns` - Do not use Babel's helper's and just transform to use the built-in method (Disabled by default).
```js
{
"plugins": [
["transform-object-rest-spread", { "useBuiltIns": true }]
]
}
// source
z = { x, ...y };
// compiled
z = Object.assign({ x }, y);
```
### Via CLI
```sh

View File

@ -15,6 +15,11 @@ export default function ({ types: t }) {
ObjectExpression(path, file) {
if (!hasSpread(path.node)) return;
let useBuiltIns = file.opts.useBuiltIns || false;
if (typeof useBuiltIns !== "boolean") {
throw new Error("transform-object-rest-spread currently only accepts a boolean option for useBuiltIns (defaults to false)");
}
let args = [];
let props = [];
@ -39,7 +44,11 @@ export default function ({ types: t }) {
args.unshift(t.objectExpression([]));
}
path.replaceWith(t.callExpression(file.addHelper("extends"), args));
const helper = useBuiltIns ?
t.memberExpression(t.identifier("Object"), t.identifier("assign")) :
file.addHelper("extends");
path.replaceWith(t.callExpression(helper, args));
}
}
};

View File

@ -0,0 +1,4 @@
{
"plugins": [["transform-object-rest-spread", { "useBuiltIns": "invalidOption" }]],
"throws": "transform-object-rest-spread currently only accepts a boolean option for useBuiltIns (defaults to false)"
}

View File

@ -0,0 +1 @@
z = Object.assign({ x }, y);

View File

@ -0,0 +1,3 @@
{
"plugins": [["transform-object-rest-spread", { "useBuiltIns": true }]]
}