Skip to content

benjroy/react-docgen-imported-proptype-handler

 
 

Repository files navigation

react-docgen handler for processing imported variables

Install

# install peer dependencies
npm install [email protected] [email protected] --save-dev
# install this handler
npm install react-docgen-imported-proptype-handler --save-dev
peerDependencies

note: it is necessary for this handler and react-docgen to share the same recast dependency

npm ls recast

should show recast as deduped under react-docgen

<project name>@<project version>
├─┬ [email protected]
│ └── [email protected]  deduped
└── [email protected]

Usage example

const { readFileSync, writeFileSync } = require('fs');
const { resolve, basename } = require('path');
const docgen = require('react-docgen');
const glob = require('glob');
const importedProptypesHandler = require('react-docgen-imported-proptype-handler').default;

const FILES = glob.sync('src/components/**/*.{js,jsx}');

const metadata = FILES.reduce((memo, filepath) => {
  /* append display name handler to handlers list */
  const handlers = docgen.defaultHandlers.concat([
    importedProptypesHandler(filepath)
  ]);

  /* read file to get source code */
  const code = readFileSync(filepath, 'utf8');

  /* parse the component code to get metadata */
  try {
    const data = docgen.parse(code, null, handlers);
    memo[basename(filepath)] = data;
  } catch (err) {
    if (err.message !== 'No suitable component definition found.') {
      console.log('ERROR:', filepath, err);
    }
  }

  return memo;
}, {});


writeFileSync(resolve(process.cwd(), 'DOCGEN_OUTPUT.json'), JSON.stringify(metadata, null, 2));

Credit

Inspiration for this came from:

Why?

react-docgen doesn't allow you to use variables from other files to use in propTypes

Example:

import iconNames from './icon-names.js'

Icon.propTypes = {
  /** Icon name */
  name: PropTypes.oneOf(iconNames).isRequired
}

This doesn't work because it's parsed as a string and not an array

"props": {
  "name": {
    "type": {
      "name": "enum",
      "computed": true,
      "value": "iconNames"
    },
    "required": true,
    "description": "Icon name"
  },
}

License

MIT © benjroy

Like it?

⭐ this repo

About

evaluate variables from external files for react-docgen

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%