Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions libs/babel-transform-react-display-name/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,14 @@ module.exports = function ({ types: t }) {

if (!isExpressionFn) return

// Should only apply to top level components
const parentStatement = componentFn.getStatementParent()
if (!t.isProgram(parentStatement.parent)) {
return
}

const declarator = componentFn.findParent((path) => t.isVariableDeclarator(path))
if (declarator) {
const parentStatement = componentFn.getStatementParent()
const name = declarator.node.id.name
parentStatement.insertAfter(genDisplayName(path, name))
return
Expand All @@ -66,11 +71,10 @@ module.exports = function ({ types: t }) {
t.isAssignmentExpression(path)
)
if (assignmentExpression) {
const parentStatement = componentFn.getStatementParent()
const leftHandSide = assignmentExpression.node.left

// Only want to do this step for top level components
if (!t.isProgram(parentStatement.parent) || !t.isMemberExpression(leftHandSide)) {
// Don't add display names to nested member expressions
if (!t.isMemberExpression(leftHandSide)) {
return
}

Expand Down
23 changes: 23 additions & 0 deletions libs/babel-transform-react-display-name/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,29 @@ describe('classed template tag literals', () => {
})
})

describe('cases that should not be transformed', () => {
it('should not transform a non-top level JSX function', () => {
const result = transform`
export function f() {
const nestedComponent = () => <div/>
}
`

expect(result).toMatchInlineSnapshot(`
"\\"use strict\\";

Object.defineProperty(exports, \\"__esModule\\", {
value: true
});
exports.f = f;

function f() {
const nestedComponent = () => /*#__PURE__*/React.createElement(\\"div\\", null);
}"
`)
})
})

/**
* Helper to streamline babel transforms
*/
Expand Down