Merge pull request #5886 from yavorsky/7-fix-commonjs-destructuring

7.0 port: Fix commonjs exports with destructuring.
This commit is contained in:
Sven SAULEAU 2017-06-26 22:37:39 +02:00 committed by GitHub
commit 692e51609c
15 changed files with 74 additions and 4 deletions

View File

@ -14,6 +14,7 @@
"babel-plugin"
],
"devDependencies": {
"babel-helper-plugin-test-runner": "7.0.0-alpha.12"
"babel-helper-plugin-test-runner": "7.0.0-alpha.12",
"babel-plugin-syntax-object-rest-spread": "7.0.0-alpha.12"
}
}

View File

@ -300,15 +300,43 @@ export default function () {
const id = decl.get("id");
const init = decl.get("init");
const exportsToInsert = [];
if (!init.node) init.replaceWith(t.identifier("undefined"));
if (id.isIdentifier()) {
addTo(exports, id.node.name, id.node);
init.replaceWith(buildExportsAssignment(id.node, init.node).expression);
nonHoistedExportNames[id.node.name] = true;
} else {
// todo
} else if (id.isObjectPattern()) {
for (let i = 0; i < id.node.properties.length; i++) {
const prop = id.node.properties[i];
let propValue = prop.value;
if (t.isAssignmentPattern(propValue)) {
propValue = propValue.left;
} else if (t.isRestProperty(prop)) {
propValue = prop.argument;
}
addTo(exports, propValue.name, propValue);
exportsToInsert.push(buildExportsAssignment(propValue, propValue));
nonHoistedExportNames[propValue.name] = true;
}
} else if (id.isArrayPattern() && id.node.elements) {
for (let i = 0; i < id.node.elements.length; i++) {
let elem = id.node.elements[i];
if (!elem) continue;
if (t.isAssignmentPattern(elem)) {
elem = elem.left;
} else if (t.isRestElement(elem)) {
elem = elem.argument;
}
const name = elem.name;
addTo(exports, name, elem);
exportsToInsert.push(buildExportsAssignment(elem, elem));
nonHoistedExportNames[name] = true;
}
}
path.insertAfter(exportsToInsert);
}
path.replaceWith(declaration.node);
}

View File

@ -0,0 +1,5 @@
"use strict";
const [foo, bar = 2] = [];
exports.foo = foo;
exports.bar = bar;

View File

@ -0,0 +1 @@
export const [foo, bar, ...baz] = [];

View File

@ -0,0 +1,6 @@
"use strict";
const [foo, bar, ...baz] = [];
exports.foo = foo;
exports.bar = bar;
exports.baz = baz;

View File

@ -0,0 +1,5 @@
"use strict";
const [foo, bar] = [];
exports.foo = foo;
exports.bar = bar;

View File

@ -0,0 +1,5 @@
"use strict";
const { foo, bar = 1 } = {};
exports.foo = foo;
exports.bar = bar;

View File

@ -0,0 +1 @@
export const { foo, ...bar } = {};

View File

@ -0,0 +1,5 @@
"use strict";
const { foo, ...bar } = {};
exports.foo = foo;
exports.bar = bar;

View File

@ -0,0 +1 @@
export const { foo: bar, baz } = {};

View File

@ -0,0 +1,5 @@
"use strict";
const { foo: bar, baz } = {};
exports.bar = bar;
exports.baz = baz;

View File

@ -1,3 +1,7 @@
{
"plugins": ["external-helpers", ["transform-es2015-modules-commonjs", { "strict": true }]]
"plugins": [
"external-helpers",
"syntax-object-rest-spread",
["transform-es2015-modules-commonjs", { "strict": true }]
]
}