Component Library Docs with Storybook

· 1 min read · 449 Words · -Views -Comments

I’ve been building a component library. To promote adoption, I set up docs. After comparing options, I chose Storybook — popular and fits the needs. The framework is simple but there were some gotchas; notes below.

Usage

# 初始化
$ npx sb init

# 热启动,即可WEB浏览
$ npm run storybook

Notes

sb init is not made for empty projects — run init at the component library root (not an empty folder). Storybook merges its config into your existing project.

Details

After initialization, you can view the docs. Next steps are custom configuration and writing example stories.

Project files

Key files in the docs setup:

  1. .storybook文件夹中即为文档相关配置

    1. main.js

      主配置,无论是打包还是预览均需要

    2. preview.js

      预览的相关配置

  2. Files ending with .stories.tsx are the docs stories. You can also use MDX.

Component stories.tsx

  • Use / in title to create nested menus (2+ levels).

  • Two ways to document components:

    • Add multi‑line comments above the component class/function.
    • Add multi‑line comments to props/fields.

    Use multi‑line comment syntax for both.

Common issues

  1. Importing global CSS

If components depend on global styles, import them in .storybook/preview.js.

import 'tea-component/dist/tea.css';
  1. Exclude stories from package builds

Source and docs live together; exclude story files from the library’s tsconfig used for packaging.

{
 "exclude": [
    "node_modules",
    "test/**/*",
    "lib/**/*.stories.tsx"
  ]
}

For the root tsconfig used by the app, still include stories to keep type safety.

  1. Global i18n init

    For global initialization (like i18n), run it in .storybook/preview.js, similar to global CSS.

    const translation = {};
    // 初始化国际化词条
    i18n.init({translation});
    
  2. Parsing error: “parserOptions.project” has been set for @typescript-eslint/parser.

Parsing error: “parserOptions.project” has been set for @typescript-eslint/parser. The file does not match your project config: lib/button.stories.tsx. The file must be included in at least one of the projects provided.

This occurs when ESLint points to a tsconfig that doesn’t include the current file. Fix by updating include to cover story files.

  1. Default export of the module has or is using private name ‘HeaderProps’

  2. Prop description not hot‑updating?

When editing prop comments, descriptions may not refresh immediately.

延伸

参考资料

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover