Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize: Simplify the export-default-from transform #14768

Merged
merged 2 commits into from Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 7 additions & 14 deletions packages/babel-plugin-proposal-export-default-from/src/index.ts
Expand Up @@ -11,33 +11,26 @@ 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 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,2 @@
import _v from "mod";
export { _v as v };
export { default as v } from "mod";
export { x, y as w } from "mod";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Further optimization idea: we can merge { default as v } with the next specifier if exists.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure. And here come a case

export v, * as ns, { x, y as w } from "mod"; 

if there is a namespace compound, should we merge it?

// a.js
export { default as v,  x, y as w} from "mod";
export * as ns from "mod";

The export order will change.

import * as ns from "a.js";
Object.keys(ns) // order changed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, it will be merged if there is no namespace export.

@@ -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";