Document your Typescript React components with TSDoc and export into Storybook-friendly JSON 🤖

Overview

react-tsdoc

react-tsdoc is an WIP tool to extract information from React Typescript component files with TSDoc for documentation generation purposes that elaborates on the TSDoc standard; in fact, it's based on the @microsoft/tsdoc parser.

Instead of doing traditional interface documentation, react-tsdoc opts in for a custom TSDoc tag named @prop which allows you to document a component like the following:

/**
 * Slick button
 *
 * @prop label - Sets the button text
 */
const Button = ({
  label
}: {
  label: string
}) => (
  <button>{label}</button>
);

or

interface ButtonProps {
  label: string
};

/**
 * Slick button
 *
 * @prop label - Sets the button text
 */
const Button = ({
  label
}: ButtonProps) => (
  <button>{label}</button>
);

Similar to react-docgen, react-tsdoc is a low level tool to extract information about React components. I am currently working on a Babel plugin that works with this project to integrate with Storybook.

Install

To install react-tsdoc just run:

npm install react-tsdoc

Example parser command:

react-tsdoc ./src/components --output ./docs/output.json

Why @prop?

I've seen a lot of codebases that define interfaces at the JSDoc "block" level, instead of "inline" comments above each interface key. On a personal stylistic note, I prefer the former, and additionally, as TSDoc does not allow interface definitions at the top-level, I didn't have much of a choice but to write my own parser.

Basically @prop Foo - Bar at the top of a React component would be the same as writing:

/**
 * Bar
 */

At the interface level. It's not a large change and as TSDocs allows extending the types via tsdoc.json file, it should still be pretty happy.

Of course, you'll still want to use normal "inline" interface descriptions for your more (not React component) interfaces.

Adding to tsdoc.json

Adding support for the @prop tag to your TSDoc config is easy! Create a tsdoc.json if you don't already have one and add this to it:

{
  "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json",
  "tagDefinitions": [
    {
      "tagName": "@prop",
      "syntaxKind": "block"
    }
  ]
}

Another Docgen?

Though react-docgen, typedoc, and react-docgen-typescript are all wonderful tools, defining props can be a challenge, especially if you are destructuring props.

As Shilman of Storybook noted in this Gist, Storybook plans to adopt react-docgen for SB7, however react-docgen is based on an outdated Doc parser (doctrine) and does not support the TSDoc standard.

I have found that interface documentation can be rather cumbersome and being able to see what each respective prop is used for at a glance is extremely handy.

Ultimately, this is just an excuse for me to play around with ASTs, but I hope others find some use in this project.

Output

Here's an example component with the associated parser output...

Input

/**
 * Button
 *
 * @prop disabled - Sets if field is disabled
 * @prop label - Sets the button text
 */
const Button = ({
	disabled = false,
	label
}: {
	disabled?: boolean
	label: string
}) => {
	return (
		<button disabled={disabled}>
			{label}
		</button>
	)
};

Output

{
  "description": "Button",
  "props": {
    "disabled": {
      "description": "Sets if field is disabled",
      "required": false,
      "tsType": {
        "name": "boolean"
      },
      "defaultValue": {
        "value": "false",
        "computed": false
      }
    },
    "label": {
      "description": "Sets the button text",
      "required": true,
      "tsType": {
        "name": "string"
      }
    }
  }
}

Supported Types

  • Simple (foo: string, bar: boolean)
  • Literals (foo: 'bar')
  • Tuples (foo: [string, number])
  • Unions (foo: string | boolean)
  • Typed arrays (foo: string[])
  • Object signatures ({ foo: string})
  • Index signatures ([foo: string]: string)
  • Function signatures (foo: (x: string) => void)
  • Intersect (foo: string & number)
  • Nullable modifier (foo: ?number)
  • Typed classes (foo: Class<bar>)

Extended support coming soon.

Development

I've heavily commented a lot of the functions as this has been an AST learning experience for me, and I hope others find it easy to understand and contribute.

To build, just run:

npm install && npm run build

This will build the ./lib folder and then you can execute the CLI from the /bin directory, like this:

bin/react-tsdoc.js ./src/components ./output.json && cat ./output.json

To run the tests:

npm run test
Issues
  • Write Tests

    Write Tests

    It's imperative to write some tests for the various functions in the parser.

    ~Thinking about using Jest, but debating between a centralized tests folder or directory-specific __tests__ folders.~

    Settled on the __tests__ folder convention.

    Files to write tests for:

    • [x] utils/paramsHelper.ts
    • [x] utils/reactComponentHelper.ts
    • [x] utils/tsDocHelper.ts
    • [x] utils/tsTypesHelper.ts
    • [x] parser.js
    enhancement 
    opened by noahbuscher 1
  • Improve React Component Helper

    Improve React Component Helper

    Right now the tool basically just checks if a variable is the default export, has a capital first letter, and is a variable declaration or function declaration. It might be smart to see if the component returns JSX or a React function.

    enhancement 
    opened by noahbuscher 0
  • Write Webpack Loader

    Write Webpack Loader

    It'll be important to write a Webpack loader to affix the __docgenInfo to the components with the doc object so this works as expected with Storybook, considering that Storybook does not allow shoe-horning in a custom docgen.

    Perhaps worth making a more generalized loader and providing a config for react-tsdoc? Seems like a common(ish) want.

    Read more here.

    enhancement 
    opened by noahbuscher 0
  • Add Support for Types

    Add Support for Types

    Imperative to add support for rolling up types into the docs.

    Take a look at this table for how to format various types as you come across them.

    Progress:

    • [x] Simple types
    • [x] Literals
    • [ ] Typed classes
    • [x] Object signatures
    • [x] Function signatures
    • [x] Callable-object / function-object signatures
    • [x] Tuple
    • [x] Union
    • [ ] Intersect
    • [ ] Nullable modifier
    enhancement 
    opened by noahbuscher 0
Owner
Noah Buscher
Better done than perfect.
Noah Buscher
Storybook-addon-message-bus - Interact with message bus via Storybook UI

Storybook Addon Message Bus Storybook Addon w/ GUI for interacting with Message

Prashis 2 Jan 8, 2022
Use vitejs, storybook and typescript to build great react components and documents.

react-component-storybook Use vitejs, storybook and typescript to build great react components. Just click Use this template button or use gh cli gh r

Jeason 5 Jan 10, 2022
Boilerplate-tailwind - A simple boilerplate using NextJS, Typescript, Tailwind, Jest, Storybook and more

This is a Next.js boilerplate using TailwindCSS and other cool stuff. Most of th

React Avançado 4 Jan 13, 2022
The friendly typescript-compatible express middleware.

useYup The friendly typescript-compatible express middleware and react hook. Installation Using npm: npm install use-yup or if you prefer to use the y

LVK.SH 1 Dec 21, 2021
Clean Typescript React project with working Storybook using Yarn

Getting Started with Create React App This project was bootstrapped with Create React App. Clone this repository To clone this repository, use the fol

Mads Skov Schiellerup 1 Nov 3, 2021
This is a very simple boilerplate made with CRA, React Router, Styled Components and Storybook.

This is a Create React App boilerplate with some configurations from React Avançado Course. What is inside? This project uses lot of stuff as: Create

React Avançado 19 Dec 22, 2021
A Simple, ATS friendly and Fast Resume Builder React App

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Mohit kumar 1 Dec 29, 2021
This is a boilerplate using webpack, react, redux, typescrpit, storybook

BOILERPLATE What's Included redux redux-persist redux middleware [Thunk & logger] redux toolkit redux devtools extentions types for react state, dispa

Md. Jahid Hasan Shuvo 12 Jan 5, 2022
A growing collection of responsive Chakra UI Templates ready to drop into your React project.

A growing collection of responsive Chakra UI Templates ready to drop into your React project.

Achim Rolle 658 Jan 18, 2022
React-Typescript-Webpack was config with React, Typescript, and Webpack without CRA. Faster to start your next react project.

Start your react typescript project with manual webpack config in seconds Flexible to control webpack, easy to deploy Keywords: React Starter, Webpack

jdn97 50 Nov 28, 2021
React-contact-management-app - A Contact Management App Using React and JSON

About In this appliication user can add a contact, delete, update amd serach a c

Devanshu Desai 1 Dec 31, 2021
Initial directory structure and package.json as a seed for new React based projects.

React Project Seed This serves as a seed for starting new React projects. It's less of a boilerplate and more of a suggested directory structure that

Andrew Coelho 7 Apr 7, 2020
A block explorer using REACTjs and the JSON RPC API

Info about this particular Block Explorer This block explorer allows the user to filter using either block number, transaction hash, or address. On th

null 6 Sep 14, 2021
Personal Website UI Template using React-TypeScript. I hope, it will be helpful for your personal website that showcases your work as a software developer.

Personal Website Template Personal Website UI Template using React-TypeScript Class components Personal website can be about anything you want, includ

Sayan Bhattacharyya 7 Aug 20, 2021
generate forms from JSON object

json-obj-form-generator generate forms from JSON object Install npm install --save json-obj-form-generator For more informations check documentation w

Radovan Pranda 11 Nov 10, 2021
Visualize your React components as you interact with your application.

Visualize your React components as you interact with your application. Setup Install React Scope from Chrome web store. (Important) Install React Deve

React Scope 317 Oct 27, 2021
An npm package that lets you jump right into coding React and Redux with universal (isomorphic) rendering. Only manage Express setups or Webpack configurations if you want to.

Universal Redux What and Why Universal Redux is an npm package that when used as a dependency in your project provides a universal (isomorphic) render

Buck DeFore 461 Dec 15, 2021
🏗️ WIP React portfolio landing page using some common libraries, with planned Apollo integration into github API. (WIP)

?? React Portfolio Portfolio One-Pager made with ReactJs Live Preview Home background effect made with React-Particles ??️ Packages & APIs React graph

Matthew Jigalin 13 Jan 17, 2022
Warp `TinyMCE` into `React Component`

mb-react-tinymce Online DEMO Try to deal with: Warp TinyMCE into React Component Also provides a hackable EditorToolbar Component Basic Usage You can

MockingBot 3 Aug 29, 2019