Description
Hello! First and most importantly, many thanks for maintaining such an amazing library.
Second, I've encountered an error in what might be an unsupported use case, but I hope my proposed solution is of general use.
I've written a custom handler that recurses through imports and object spreads to resolve prop types defined in other source files, so that their documentation can be included in the documentation of any "derived" components. I'm sure you've seen many similar efforts out there, but for the sake of clarity here's my simple use case:
A.jsx
import React from 'react';
import PropTypes from 'prop-types';
const A = ({ foo, bar }) => (
<div>{foo}{bar}</div>
);
A.propTypes = {
/**
* Fooiness
*/
foo: PropTypes.string,
/**
* Bariness
*/
bar: PropTypes.string,
};
A.defaultProps = {
foo: '',
bar: '',
};
export default A;
B.jsx
import React from 'react';
import PropTypes from 'prop-types';
import A from './A';
const B = ({ baz, ...props }) => (
<div>
{baz}
<A {...props} />
</div>
);
B.propTypes = {
...A.propTypes,
/**
* Baziness
*/
baz: PropTypes.string,
};
B.defaultProps = {
...A.defaultProps,
baz: '',
};
export default B;
To include these imported prop types in a derived component's documentation, my handler takes the Property
-typed AST nodes from the source component's propTypes
Object and inserts them into the target component's propTypes
Objects.
This approach was working well until I updated to a more recent version of react-docgen
(from v4.1.1 to v5.3.1), when I started getting what seemed like garbled output in some of my defaultProps
, and custom prop type names in propTypes
(like RefPropType
, for example) had been replaced with the string 'custom'
.
I tracked the issue down to the current implementation of printValue
which recurses up through ancestors in the AST to get the source code from the File
node and then use's the original node's start
and end
character indexes to grab a substring from this source.
The Property
nodes that I inserted from other source files have start
and end
character indexes that are totally invalid for the source associated with the AST that they are copied into, which is why I'm getting random characters, or none at all.
I was hoping that by using something like @babel/types
's cloneDeepWithoutLoc
in my handler, I could strip out all the source location info and react-docgen
would fall back to another printing method that didn't rely on the original source. Turns out only Literal
-type nodes are supported this way.
This is a very longwinded way of proposing that, if printValue
encounters a node without source location metadata, react-docgen
fall back to a printer like @babel/generator
or recast.print
. I hope that sounds reasonable to you. Anticipating that it might be, I've put together a PR which I will submit shortly.
Thanks again, and Happy New Year!