TypeScript + React 构建组件库 -- 配置篇(二)

1,891 阅读2分钟

TypeScript + React 构建组件库 -- 配置篇(一)

目标

使用 react + typescript 写组件库,发布至 npm,支持按需加载,有文档,单元测试和 CI

项目地址

项目地址 文档

本文主要记录开发过程中遇到的一些配置问题,以及如何解决的。可能不是最好的解决方案,但总归还是解决了吧,如果有人遇到相同问题的可以参考一下。

文档配置

我生成文档用的是 react-styleguidist

webpack 配置

  const webpackConfig = require("./config/webpack.config.js")(process.env.NODE_ENV);

  module.exports = {
    ...
    webpackConfig,
    ...
  }

自动根据组件参数生成文档

module.exports = {
  ...
  propsParser: require("react-docgen-typescript").withCustomConfig(
    "./tsconfig.json",
    {
      shouldExtractLiteralValuesFromEnum: true,
      savePropValueAsString: true,
      shouldRemoveUndefinedFromOptional: true,
      propFilter: (prop, component) => {
        if (prop.parent) {
          return !prop.parent.fileName.includes("node_modules");
        }

        return true;
      },
    }
  ).parse
  ...
}

  • react-docgen-typescript 是为了支持 TS
  • withCustomConfig 的第二个参数是使用自定义的解析方式,以上参数在 react-docgen-typescriptREADME.md 都有介绍,可以顾名思义,或者直接谷歌翻译。我的这些配置想要达到的效果就是
    • shouldExtractLiteralValuesFromEnum 使如下代码的生成的文档里显示的类型是 large | middle | small 而不是 sizeType
      type sizeType = "large" | "middle" | "small";
      interface Props {
        size?: sizeType;
      }
      
    • savePropValueAsString 使如下代码的生成的文档里显示的类型是 aaa | 0 而不是 string | number
      interface Props {
        aaa: "aaa" | 0;
      }
      
    • shouldRemoveUndefinedFromOptional,这个就是把 undefined 这个类型从文档中去掉
    • propFilter,其后面配置的函数是为了防止如下代码把 React.SVGAttributes<SVGElement> 的一些字段都显示在文档里
      interface Props extends React.SVGAttributes<SVGElement> {}
      

修改文档的样式

module.exports = {
  ...
  require: [path.join(__dirname, "styleguide.styles.css")],
  ...
}
/* styleguide.styles.css */
td:nth-child(2) {
  max-width: 500px !important;
  min-width: 300px !important;
}

修改组件文档里参数的排序

默认是按照开头字母顺序排序,但是我希望按照我代码里的顺序排序

module.exports = {
  ...
  sortProps: (props) => props
  ...
}

文档太长

文档太长时可以用这个配置,让每个组件的文档都是单独的页面

module.exports = {
  ...
  pagePerSection: true,
  ...
}

修改文档结构

module.exports = {
  ...
  sections: [
    {
      name: "介绍",
      content: "introduction.md",
    },
    {
      name: "基础组件",
      components: [
        "src/components/Button/Button.tsx",
        "src/components/Icon/Icon.tsx",
      ],
      sectionDepth: 1,
    },
    {
      name: "布局组件",
      components: ["src/components/Col/Col.tsx", "src/components/Row/Row.tsx"],
      sectionDepth: 1,
    },
    ...
  ]
  ...
}

以上就是使用 react-styleguidist 生成文档的配置要点,接下来还有单元测试和 CI