Skip to content

Commit

Permalink
optimize: Simplify the export-default-from transform (#14768)
Browse files Browse the repository at this point in the history
* optimize: Simplify the `export-default-from` transform

* chore: merge specifiers if possible
  • Loading branch information
magic-akari committed Jul 19, 2022
1 parent ff6304b commit f2ba41b
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 23 deletions.
31 changes: 15 additions & 16 deletions packages/babel-plugin-proposal-export-default-from/src/index.ts
Expand Up @@ -11,33 +11,32 @@ export default declare(api => {

visitor: {
ExportNamedDeclaration(path) {
const { node, scope } = path;
const { specifiers } = node;
const { node } = path;
const { specifiers, source } = node;
if (!t.isExportDefaultSpecifier(specifiers[0])) return;

const specifier = specifiers.shift();
const { exported } = specifier;
const uid = scope.generateUidIdentifier(
// @ts-expect-error Identifier ?? StringLiteral
exported.name ?? exported.value,
);
const { exported } = specifiers.shift();

if (specifiers.every(s => t.isExportSpecifier(s))) {
specifiers.unshift(
t.exportSpecifier(t.identifier("default"), exported),
);
return;
}

const nodes = [
t.importDeclaration(
[t.importDefaultSpecifier(uid)],
t.cloneNode(node.source),
t.exportNamedDeclaration(
null,
[t.exportSpecifier(t.identifier("default"), exported)],
t.cloneNode(source),
),
t.exportNamedDeclaration(null, [
t.exportSpecifier(t.cloneNode(uid), exported),
]),
];

if (specifiers.length >= 1) {
nodes.push(node);
}

const [importDeclaration] = path.replaceWithMultiple(nodes);
path.scope.registerDeclaration(importDeclaration);
path.replaceWithMultiple(nodes);
},
},
};
Expand Down
@@ -1,3 +1 @@
import _v from "mod";
export { _v as v };
export { x, y as w } from "mod";
export { default as v, x, y as w } from "mod";
@@ -1,2 +1 @@
import _foo from "bar";
export { _foo as foo };
export { default as foo } from "bar";
@@ -1,2 +1 @@
import _foo from "bar";
export { _foo as foo };
export { default as foo } from "bar";

0 comments on commit f2ba41b

Please sign in to comment.