forked from TeamWertarbyte/react-props-md-table
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild-props-table.js
44 lines (36 loc) · 1.73 KB
/
build-props-table.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const reactDocs = require('react-docgen');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const stripComments = require('./strip-comments');
const formatType = require('./format-type');
const nlToBr = require('./nl-to-br');
const addLine = require('./add-line');
const buildPropsTable = (filename) => {
try {
const content = fs.readFileSync(path.resolve(process.cwd(), filename), 'utf-8');
const components = reactDocs.parse(content, reactDocs.resolver.findAllExportedComponentDefinitions);
let propsTable = '';
components.forEach((component) => {
const title = components.length > 1 ? `## ${component.displayName || ''} Properties` : '## Properties';
propsTable = addLine(propsTable, title);
propsTable = addLine(propsTable);
if (component.props) {
propsTable = addLine(propsTable, '| Property | PropType | Required | Default | Description |');
propsTable = addLine(propsTable, '|----------|----------|----------|---------|-------------|');
for (const name of Object.keys(component.props)) {
const { type, required, description, defaultValue } = component.props[name];
propsTable = addLine(propsTable, `| ${name} | \`${formatType(type)}\` | ${required ? 'yes' : ''} | ${defaultValue != null ? `\`${nlToBr(stripComments(defaultValue.value), true)}\`` : ''} | ${nlToBr(description)} |`);
}
} else {
propsTable = addLine(propsTable, 'This component has no properties');
}
propsTable = addLine(propsTable);
});
return propsTable;
} catch (e) {
console.error(chalk.red(`Can't extract props data from file ${filename}: ${e.message}`));
return null;
}
}
module.exports = buildPropsTable;