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

Register binding for newly created vars for commonjs transforms #14097

Merged
merged 1 commit into from Jan 6, 2022
Merged
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
6 changes: 6 additions & 0 deletions packages/babel-plugin-transform-modules-commonjs/src/index.ts
Expand Up @@ -235,6 +235,12 @@ export default declare((api, options) => {

ensureStatementsHoisted(headers);
path.unshiftContainer("body", headers);
path.get("body").forEach(path => {
if (headers.indexOf(path.node) === -1) return;
if (path.isVariableDeclaration()) {
path.scope.registerDeclaration(path);
}
Comment on lines +238 to +242
Copy link
Member

Choose a reason for hiding this comment

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

Note for reviewers: this code is the same as

this.path.unshiftContainer("body", nodes);
// TODO: NodePath#unshiftContainer should automatically register new
// bindings.
this.path.get("body").forEach(path => {
if (nodes.indexOf(path.node) === -1) return;
if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);
});

});
},
},
},
Expand Down
@@ -0,0 +1,5 @@
import {x} from './foo.js';
var y = true;
function f() {
return [x, y, console];
}
@@ -0,0 +1,4 @@
{
"sourceType": "module",
"plugins": ["transform-modules-commonjs", "./plugin"]
}
@@ -0,0 +1,15 @@
"use strict";

var _foo = require("./foo.js");

var y = true;

function f() {
return [
/* _foo hasBinding, getBinding */
_foo.x,
/* y hasBinding, getBinding */
y,
/* console no hasBinding, no getBinding */
console];
}
@@ -0,0 +1,29 @@
module.exports = function () {
return {
visitor: {
Program: {
exit(programPath) {
// Sub-traversal to ensure runs after ESM->CJS transform
programPath.traverse({
ReferencedIdentifier(path) {
if (!path.findParent(p => p.isFunction())) return;
const varName = path.node.name;
path.addComment(
"leading",
` ${varName} ${
path.scope.hasBinding(varName)
? "hasBinding"
: "no hasBinding"
}, ${
path.scope.getBinding(varName)
? "getBinding"
: "no getBinding"
} `
);
},
});
},
},
},
};
};