最近一直在捣鼓如何搭建实用的组件库,至于为何会产生这个想法,主要是由于组件库对于前端生态来讲究极重要,每个着眼于长远发展的互联网公司基本上都会量身定制组件库,它的好处不用多说,读者们在使用中或多或少都会体会到一些优势,若是之前作过MVC,那么对于这一点的体会确定更加深入。一款组件库如此之重要,做为一名前端工程师应该去深刻的了解,为之后任务开发、职业发展赋能。css
大体来讲,开发一款组件库一般会有如下几点好处:前端
在作任何一件事情以前都应该捋清楚咱们的初衷,也就是咱们的需求是什么,凡事预则立,不预则废。react
这里撇开业务上的需求,由于这篇文章没有基于业务场景去考虑。只梳理一些功能上需求,也就是如何搭建一个高性能、高实用、高标准的React组件库。webpack
需求清单:web
搭建组件库首先咱们来搭建工程环境,这里咱们不采用create-react-app脚手架来搭建,由于脚手架封装好了不少东西,而有些东西对于组件库并不适用,用来搭建组件库过于臃肿。所以,我准备从零到一搭建React组件库。npm
首先,先建立一个工程文件夹,执行npm init
命令生成package.json
;执行tsc --init
生成tsconfig.json
json
而后,按以下结构组织工程的目录结构:前端工程师
pony-react-ui - src - assets // 存放静态文件,好比图片、文字等 - components // 组件 - styles // 组件样式 - index.ts // 主文件入口 - style.ts // 样式文件入口 - package.json // 依赖管理 - tsconfig.json // ts配置 - webpack.config.js // webpack配置
在components文件夹下以以下方式组织组件,好比建立一个Button组件app
- components - Button - Button.tsx // 按钮组件 - index.tsx // 组件入口 - Dialog - Dialog.tsx - index.tsx
Button.tsx性能
import React from 'react'; import classNames from 'classnames'; export interface IButtonProps { onClick?: React.MouseEventHandler; // 类型 primary?: boolean; secondary?: boolean; outline?: boolean; dashed?: boolean; link?: boolean; text?: boolean; // 尺寸 xLarge?: boolean; large?: boolean; small?: boolean; xSmall?: boolean; xxSmall?: boolean; // 颜色 success?: boolean; warn?: boolean; danger?: boolean; // 禁用状态 disabled?: boolean; className?: string; style?: React.CSSProperties; children?: React.ReactNode; } export const Button = (props: IButtonProps) => { const { className: tempClassName, style, onClick, children, primary, secondary, outline, dashed, link, text, xLarge, large, small, xSmall, xxSmall, success, danger, warn, disabled, } = props; const className = classNames( { 'pony-button': true, 'pony-button-primary': primary, 'pony-button-secondary': secondary && !text, 'pony-button-outline': outline, 'pony-button-dashed': dashed, 'pony-button-link': link, 'pony-button-text': text && !secondary, 'pony-button-text-secondary': secondary && text, 'pony-button-round': round, 'pony-button-rectangle': noRadius, 'pony-button-fat': fat, 'pony-button-xl': xLarge, 'pony-button-lg': large, 'pony-button-sm': small, 'pony-button-xs': xSmall, 'pony-button-xxs': xxSmall, 'pony-button-long': long, 'pony-button-short': short, 'pony-button-success': success, 'pony-button-warn': warn, 'pony-button-danger': danger, 'pony-button-disabled': disabled, }, tempClassName ); return ( <button type="button" className={className} style={style} onClick={onClick} disabled={disabled}> <span className="pony-button__content">{children}</span> </button> ); }
在index.tsx抛出组件以及该组件的类型声明
export * from './Button';
- styles -
我把组件的样式都存放在/src/styles文件夹中,除了存放各个组件样式以外,另外建立_minxin.scss