Skip to content

Commit

Permalink
Fix detection of ESM imports
Browse files Browse the repository at this point in the history
  • Loading branch information
danez committed Oct 12, 2023
1 parent 2262286 commit 3be404e
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/young-carrots-sort.md
@@ -0,0 +1,5 @@
---
'react-docgen': patch
---

Fix detection of React.Children with ESM imports
Expand Up @@ -21,6 +21,42 @@ describe('isReactChildrenElementCall', () => {

expect(isReactChildrenElementCall(def)).toBe(true);
});

test('React.Children.only without React', () => {
const def = parse.expressionLast(`
var Children = require("React").Children;
Children.only(() => {});
`);

expect(isReactChildrenElementCall(def)).toBe(true);
});

test('React.Children.only with destructuring', () => {
const def = parse.expressionLast(`
var { Children } = require("React");
Children.only(() => {});
`);

expect(isReactChildrenElementCall(def)).toBe(true);
});

test('React.Children.only with import', () => {
const def = parse.expressionLast(`
import React from 'react';
React.Children.only(() => {});
`);

expect(isReactChildrenElementCall(def)).toBe(true);
});

test('React.Children.only with named import', () => {
const def = parse.expressionLast(`
import { Children } from 'react';
Children.only(() => {});
`);

expect(isReactChildrenElementCall(def)).toBe(true);
});
});
describe('false', () => {
test('not call expression', () => {
Expand Down
29 changes: 10 additions & 19 deletions packages/react-docgen/src/utils/isReactChildrenElementCall.ts
@@ -1,7 +1,6 @@
import type { NodePath } from '@babel/traverse';
import isReactModuleName from './isReactModuleName.js';
import resolveToModule from './resolveToModule.js';
import type { CallExpression } from '@babel/types';
import isReactBuiltinReference from './isReactBuiltinReference.js';

/**
* Returns true if the expression is a function call of the form
Expand All @@ -16,24 +15,16 @@ export default function isReactChildrenElementCall(

const callee = path.get('callee');

if (
!callee.isMemberExpression() ||
(!callee.get('property').isIdentifier({ name: 'only' }) &&
!callee.get('property').isIdentifier({ name: 'map' }))
) {
return false;
}

const calleeObj = callee.get('object');
if (callee.isMemberExpression()) {
const calleeProperty = callee.get('property');

if (
!calleeObj.isMemberExpression() ||
!calleeObj.get('property').isIdentifier({ name: 'Children' })
) {
return false;
if (
calleeProperty.isIdentifier({ name: 'only' }) ||
calleeProperty.isIdentifier({ name: 'map' })
) {
return isReactBuiltinReference(callee.get('object'), 'Children');
}
}

const module = resolveToModule(calleeObj);

return Boolean(module && isReactModuleName(module));
return false;
}

0 comments on commit 3be404e

Please sign in to comment.