Skip to content

Commit

Permalink
Fix this compilation (#295)
Browse files Browse the repository at this point in the history
* Fix `this` compilation

* Update component.js

* Fix `this` scoping

* Fix arrow function transforms on `this`

* Fix `this` on JSXElement
  • Loading branch information
lxsmnsyc committed Nov 22, 2023
1 parent b59e255 commit 5b7b53d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { transformNode, getCreateTemplate } from "./transform";

function convertComponentIdentifier(node) {
if (t.isJSXIdentifier(node)) {
if (node.name === 'this') return t.thisExpression();
if (t.isValidIdentifier(node.name)) node.type = "Identifier";
else return t.stringLiteral(node.name);
} else if (t.isJSXMemberExpression(node)) {
Expand Down
45 changes: 37 additions & 8 deletions packages/babel-plugin-jsx-dom-expressions/src/shared/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,50 @@ export function transformJSX(path) {
path.replaceWith(replace(template(path, result, false)));
}

function getTargetFunctionParent(path, parent) {
let current = path.scope.getFunctionParent();
while (current !== parent && current.path.isArrowFunctionExpression()) {
current = current.path.parentPath.scope.getFunctionParent()
}
return current;
}

export function transformThis(path) {
const parent = path.scope.getFunctionParent();
let thisId;
path.traverse({
ThisExpression(path) {
thisId || (thisId = path.scope.generateUidIdentifier("self$"));
path.replaceWith(thisId);
}
const current = getTargetFunctionParent(path, parent);
if (current === parent) {
thisId || (thisId = path.scope.generateUidIdentifier("self$"));
path.replaceWith(thisId);
}
},
JSXElement(path) {
let source = path.get('openingElement').get('name');
while (source.isJSXMemberExpression()) {
source = source.get('object');
}
if (source.isJSXIdentifier() && source.node.name === 'this') {
const current = getTargetFunctionParent(path, parent);
if (current === parent) {
thisId || (thisId = path.scope.generateUidIdentifier("self$"));
source.replaceWith(t.jsxIdentifier(thisId.name));

if (path.node.closingElement) {
path.node.closingElement.name = path.node.openingElement.name;
}
}
}
},
});
return node => {
if (thisId) {
let parent = path.getStatementParent();
const decl = t.variableDeclaration("const", [
t.variableDeclarator(thisId, t.thisExpression())
]);
parent.insertBefore(decl);
parent.push({
id: thisId,
init: t.thisExpression(),
kind: 'const',
});
}
return node;
};
Expand Down

0 comments on commit 5b7b53d

Please sign in to comment.