Last active
April 8, 2024 12:54
-
-
Save souporserious/575609dc5a5d52e167dd2236079eccc0 to your computer and use it in GitHub Desktop.
Generate an array of React documentation using babel-plugin-preval and react-docgen.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// make sure to have babel-plugin-preval setup so this import works as expected | |
// https://github.com/kentcdodds/babel-plugin-preval | |
import docs from "./get-react-docs.js" | |
// do whatever you want with all of the component documentation | |
function renderDocs() { | |
return ( | |
<div> | |
{docs.map(doc => ...)} | |
</div> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @preval | |
const { readdirSync, readFileSync, existsSync } = require('fs') | |
const { basename, resolve } = require('path') | |
const glob = require('glob') | |
const reactDocgen = require('react-docgen') | |
const { createDisplayNameHandler } = require('react-docgen-displayname-handler') | |
const PACKAGES_DIR = './packages/**' | |
const files = glob.sync(`${PACKAGES_DIR}/[A-Z]*.js`, { | |
ignore: [`${PACKAGES_DIR}/*.example.js`, `${PACKAGES_DIR}/*.test.js`], | |
}) | |
const docs = [] | |
files.forEach((file, index) => { | |
const component = readFileSync(file).toString() | |
const name = basename(file, '.js') | |
const examplePath = file.replace('.js', '.example.js') | |
const data = { | |
name, | |
file, | |
} | |
// try to grab ${component}.example.js | |
if (existsSync(examplePath)) { | |
data.example = readFileSync(examplePath).toString() | |
} | |
// we use a try block in case react-docgen fails to create docs from the component | |
try { | |
const docGen = reactDocgen.parse( | |
component, | |
reactDocgen.resolver.findExportedComponentDefinition, | |
reactDocgen.defaultHandlers.concat(createDisplayNameHandler(name)) | |
) | |
docs.push({ | |
...data, | |
...docGen, | |
}) | |
} catch (err) {} | |
}) | |
module.exports = docs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment