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

Improve output when re-exporting #15709

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
196 changes: 130 additions & 66 deletions packages/babel-helper-module-transforms/src/index.ts
Expand Up @@ -3,9 +3,11 @@ import {
booleanLiteral,
callExpression,
cloneNode,
continueStatement,
directive,
directiveLiteral,
expressionStatement,
functionDeclaration,
identifier,
isIdentifier,
memberExpression,
Expand Down Expand Up @@ -64,9 +66,9 @@ export interface RewriteModuleStatementsAndPrepareHeaderOptions {
lazy?: Lazy;
esNamespaceOnly?: boolean;
filename: string | undefined;
constantReexports?: boolean | void;
enumerableModuleMeta?: boolean | void;
noIncompleteNsImportDetection?: boolean | void;
constantReexports?: boolean;
enumerableModuleMeta?: boolean;
noIncompleteNsImportDetection?: boolean;
}

/**
Expand Down Expand Up @@ -207,7 +209,8 @@ export function wrapInterop(
export function buildNamespaceInitStatements(
metadata: ModuleMetadata,
sourceMetadata: SourceModuleMetadata,
constantReexports: boolean | void = false,
constantReexports: boolean = false,
buildInteropWrap?: Parameters<typeof buildNamespaceReexport>[3],
) {
const statements = [];

Expand All @@ -233,17 +236,23 @@ export function buildNamespaceInitStatements(
statements.push(
(sourceMetadata.lazy
? template.statement`
Object.defineProperty(EXPORTS, "NAME", {
enumerable: true,
get: function() {
return NAMESPACE;
}
EXPORT_GETTER("NAME", function() {
return NAMESPACE;
});
`
: template.statement`EXPORTS.NAME = NAMESPACE;`)({
EXPORTS: metadata.exportName,
NAME: exportName,
NAMESPACE: cloneNode(srcNamespace),
...(sourceMetadata.lazy
? {
EXPORT_GETTER: buildExportGetter(
metadata.programPath,
metadata.exportName,
),
}
: {
EXPORTS: metadata.exportName,
}),
}),
);
}
Expand All @@ -252,6 +261,7 @@ export function buildNamespaceInitStatements(
metadata,
cloneNode(srcNamespace),
constantReexports,
buildInteropWrap,
);
statement.loc = sourceMetadata.reexportAll.loc;

Expand All @@ -265,11 +275,8 @@ const ReexportTemplate = {
constant: template.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`,
constantComputed: template.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`,
spec: template.statement`
Object.defineProperty(EXPORTS, "EXPORT_NAME", {
enumerable: true,
get: function() {
return NAMESPACE_IMPORT;
},
EXPORT_GETTER("EXPORT_NAME", function () {
return NAMESPACE_IMPORT;
});
`,
};
Expand Down Expand Up @@ -312,7 +319,11 @@ function buildReexportsFromMeta(
return ReexportTemplate.constant(astNodes);
}
} else {
return ReexportTemplate.spec(astNodes);
return ReexportTemplate.spec({
EXPORT_NAME: exportName,
NAMESPACE_IMPORT,
EXPORT_GETTER: buildExportGetter(meta.programPath, meta.exportName),
});
}
});
}
Expand All @@ -337,54 +348,106 @@ function buildESModuleHeader(
)({ EXPORTS: metadata.exportName });
}

function addPrivateHelper(
path: NodePath<t.Program>,
name: string,
fn: t.FunctionExpression,
) {
const { scope } = path;
const key = PACKAGE_JSON.name + "." + name;
let id = path.getData(key);
if (id) {
return cloneNode(id);
}
id = scope.generateUidIdentifier("_" + name);
path.setData(key, id);

const [fnPath] = path.unshiftContainer(
"body",
functionDeclaration(id, fn.params, fn.body),
);
path.scope.registerBinding("hoisted", fnPath);

return cloneNode(id);
}

function buildExportGetter(path: NodePath<t.Program>, exportName: string) {
return addPrivateHelper(
path,
"export",
template.expression`
function (name, fn) {
Object.defineProperty(EXPORTS, name, {
enumerable: true,
get: fn
});
}
`({
EXPORTS: identifier(exportName),
}) as t.FunctionExpression,
);
}

/**
* Create a re-export initialization loop for a specific imported namespace.
*/
function buildNamespaceReexport(
metadata: ModuleMetadata,
namespace: t.Identifier | t.CallExpression,
constantReexports: boolean | void,
constantReexports: boolean,
buildInteropWrap?: (reexportsStmts: t.CallExpression) => t.CallExpression,
) {
return (
constantReexports
? template.statement`
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;

EXPORTS[key] = NAMESPACE[key];
});
`
: // Also skip already assigned bindings if they are strictly equal
// to be somewhat more spec-compliant when a file has multiple
// namespace re-exports that would cause a binding to be exported
// multiple times. However, multiple bindings of the same name that
// export the same primitive value are silently skipped
// (the spec requires an "ambiguous bindings" early error here).
template.statement`
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;

Object.defineProperty(EXPORTS, key, {
enumerable: true,
get: function() {
return NAMESPACE[key];
const { programPath, exportNameListName } = metadata;

// Also skip already assigned bindings if they are strictly equal
// to be somewhat more spec-compliant when a file has multiple
// namespace re-exports that would cause a binding to be exported
// multiple times. However, multiple bindings of the same name that
// export the same primitive value are silently skipped
// (the spec requires an "ambiguous bindings" early error here).
const fn = template.expression`
function (exports, mod, exportNames) {
for (const k in mod) {
VERIFY_NAME;
(k in exports && exports[k] === mod[k]) || SET_PROPERTY;
}
}`({
VERIFY_NAME: exportNameListName
? template.statement.ast`
if (k === "default" || k === "__esModule" || exportNames.indexOf(k) >= 0) ${continueStatement()}
`
: template.statement.ast`
if (k === "default" || k === "__esModule") ${continueStatement()}
`,
SET_PROPERTY: constantReexports
? template.expression.ast`exports[k] = mod[k]`
: template.expression.ast`
Object.defineProperty(exports, k, {
get: function () {
return mod[k];
},
});
});
`
)({
NAMESPACE: namespace,
EXPORTS: metadata.exportName,
VERIFY_NAME_LIST: metadata.exportNameListName
? template`
if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;
`({ EXPORTS_LIST: metadata.exportNameListName })
: null,
});
enumerable: true
})
`,
}) as t.FunctionExpression;

if (!exportNameListName) fn.params.pop();

const fnId = addPrivateHelper(
programPath,
constantReexports ? "reexports" : "reexports2",
fn,
);
const args = [identifier(metadata.exportName), namespace];
if (exportNameListName) {
args.push(identifier(exportNameListName));
}

if (!buildInteropWrap) {
return expressionStatement(callExpression(fnId, args));
}

return expressionStatement(buildInteropWrap(callExpression(fnId, args)));
}

/**
Expand All @@ -396,35 +459,36 @@ function buildExportNameListDeclaration(
programPath: NodePath,
metadata: ModuleMetadata,
) {
const exportedVars = Object.create(null);
const exportedVars = new Set<string>();
for (const data of metadata.local.values()) {
for (const name of data.names) {
exportedVars[name] = true;
exportedVars.add(name);
}
}

let hasReexport = false;
for (const data of metadata.source.values()) {
for (const exportName of data.reexports.keys()) {
exportedVars[exportName] = true;
exportedVars.add(exportName);
}
for (const exportName of data.reexportNamespace) {
exportedVars[exportName] = true;
exportedVars.add(exportName);
}

hasReexport = hasReexport || !!data.reexportAll;
}

if (!hasReexport || Object.keys(exportedVars).length === 0) return null;
exportedVars.delete("default");
exportedVars.delete("__esModule");

const name = programPath.scope.generateUidIdentifier("exportNames");
if (!hasReexport || exportedVars.size === 0) return null;

delete exportedVars.default;
const name = programPath.scope.generateUidIdentifier("exportNames");

return {
name: name.name,
statement: variableDeclaration("var", [
variableDeclarator(name, valueToNode(exportedVars)),
variableDeclarator(name, valueToNode(Array.from(exportedVars))),
]),
};
}
Expand All @@ -436,8 +500,8 @@ function buildExportNameListDeclaration(
function buildExportInitializationStatements(
programPath: NodePath,
metadata: ModuleMetadata,
constantReexports: boolean | void = false,
noIncompleteNsImportDetection: boolean | void = false,
constantReexports: boolean = false,
noIncompleteNsImportDetection: boolean = false,
) {
const initStatements: Array<[string, t.Statement | null]> = [];

Expand Down
Expand Up @@ -6,6 +6,7 @@ import splitExportDeclaration from "@babel/helper-split-export-declaration";
import type { NodePath } from "@babel/traverse";

export interface ModuleMetadata {
programPath: NodePath<t.Program>;
exportName: string;
// The name of the variable that will reference an object containing export names.
exportNameListName: null | string;
Expand Down Expand Up @@ -176,6 +177,7 @@ export default function normalizeModuleAndLoadMetadata(
}

return {
programPath,
exportName,
exportNameListName: null,
hasExports,
Expand Down
Expand Up @@ -4,10 +4,13 @@ define(["exports", "foo"], function (_exports, _foo) {
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "foo", {
enumerable: true,
get: function () {
return _foo.foo;
}
_export("foo", function () {
return _foo.foo;
});
function _export(name, fn) {
Object.defineProperty(_exports, name, {
enumerable: true,
get: fn
});
}
});
Expand Up @@ -4,16 +4,16 @@ define(["exports", "foo"], function (_exports, _foo) {
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "bar", {
enumerable: true,
get: function () {
return _foo.bar;
}
_export("bar", function () {
return _foo.bar;
});
Object.defineProperty(_exports, "foo", {
enumerable: true,
get: function () {
return _foo.foo;
}
_export("foo", function () {
return _foo.foo;
});
function _export(name, fn) {
Object.defineProperty(_exports, name, {
enumerable: true,
get: fn
});
}
});
Expand Up @@ -4,10 +4,13 @@ define(["exports", "foo"], function (_exports, _foo) {
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "bar", {
enumerable: true,
get: function () {
return _foo.foo;
}
_export("bar", function () {
return _foo.foo;
});
function _export(name, fn) {
Object.defineProperty(_exports, name, {
enumerable: true,
get: fn
});
}
});