Skip to content

Commit

Permalink
Unshadow cjs exports when transforming mutations (#14708)
Browse files Browse the repository at this point in the history
* Add failing test

* Unshadow `cjs` exports when transforming mutations
  • Loading branch information
nicolo-ribaudo committed Jun 29, 2022
1 parent 5fdc5eb commit 1261051
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 1 deletion.
Expand Up @@ -183,6 +183,7 @@ const rewriteBindingInitVisitor: Visitor<RewriteBindingInitVisitorState> = {
metadata,
exportNames,
identifier(localName),
path.scope,
),
);
// @ts-expect-error todo(flow->ts): avoid mutations
Expand All @@ -203,6 +204,7 @@ const rewriteBindingInitVisitor: Visitor<RewriteBindingInitVisitorState> = {
metadata,
exportNames,
identifier(localName),
path.scope,
),
);
// @ts-expect-error todo(flow->ts): avoid mutations
Expand All @@ -218,7 +220,18 @@ const buildBindingExportAssignmentExpression = (
metadata: ModuleMetadata,
exportNames: string[],
localExpr: t.Expression,
scope: Scope,
) => {
const exportsObjectName = metadata.exportName;
for (
let currentScope = scope;
currentScope != null;
currentScope = currentScope.parent
) {
if (currentScope.hasOwnBinding(exportsObjectName)) {
currentScope.rename(exportsObjectName);
}
}
return (exportNames || []).reduce((expr, exportName) => {
// class Foo {} export { Foo, Foo as Bar };
// as
Expand All @@ -228,7 +241,7 @@ const buildBindingExportAssignmentExpression = (
return assignmentExpression(
"=",
memberExpression(
identifier(metadata.exportName),
identifier(exportsObjectName),
computed ? stringLiteral(exportName) : identifier(exportName),
/* computed */ computed,
),
Expand Down Expand Up @@ -352,6 +365,7 @@ const rewriteReferencesVisitor: Visitor<RewriteReferencesVisitorState> = {
this.metadata,
exportedNames,
cloneNode(update),
path.scope,
),
);
} else {
Expand All @@ -366,6 +380,7 @@ const rewriteReferencesVisitor: Visitor<RewriteReferencesVisitorState> = {
this.metadata,
exportedNames,
identifier(localName),
path.scope,
),
cloneNode(ref),
]),
Expand Down Expand Up @@ -428,6 +443,7 @@ const rewriteReferencesVisitor: Visitor<RewriteReferencesVisitorState> = {
this.metadata,
exportedNames,
assignment,
path.scope,
),
);
requeueInParent(path);
Expand Down Expand Up @@ -458,6 +474,7 @@ const rewriteReferencesVisitor: Visitor<RewriteReferencesVisitorState> = {
this.metadata,
exportedNames,
identifier(localName),
path.scope,
),
);
}
Expand Down
@@ -0,0 +1,8 @@
var exports = 1;

export let x = 2;

function fn() {
x = 3;
var exports = 4;
}
@@ -0,0 +1,3 @@
{
"plugins": ["transform-modules-commonjs"]
}
@@ -0,0 +1,14 @@
"use strict";

Object.defineProperty(exports, "__esModule", {
value: true
});
exports.x = void 0;
var _exports = 1;
let x = 2;
exports.x = x;

function fn() {
exports.x = x = 3;
var _exports2 = 4;
}

0 comments on commit 1261051

Please sign in to comment.