Home Web Front-end JS Tutorial Examples of component library development using React

Examples of component library development using React

Feb 06, 2018 pm 02:40 PM
react develop components

Recently, I used react to encapsulate a set of [component libraries] for daily business needs, and roughly recorded my experiences during the entire development process. Due to space reasons, only the selection and packaging, which are more tangled during the development process, will be discussed here, and the packaging of specific components will be discussed later. This article mainly introduces to you an example of component library development using React. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Overview

We all know that the component-based development model has greatly improved our development efficiency. Encapsulating basic components can greatly simplify our focus on the basic UI, allowing us to focus our work on business logic, and well separate the business and basic UI codes, making the entire project more manageable. This is what we want to do. The reason for the development of this component library.

However, there are many existing React open source components, such as ant-design and material-ui, etc. Whether you need to spend effort to create a component library suitable for your own team often needs to be considered appropriately. Let’s take a look at some of the characteristics of my existing team and business:

  1. There are many front-end personnel, they need to cooperate with each other, and they have enough time to develop components

  2. The product business is relatively complex and requires customized development of certain components

  3. There are already mature design specifications that define various basic components, basic styles, etc.

  4. The current project is relatively messy, and the third-party component references are messy

It can be seen that we have the energy and foundation to encapsulate our own components, and we have The need to change the current development status through basic component encapsulation. So, this is something we should and need to get done as soon as possible.

Technical selection

For the encapsulation of component libraries, the first thing we face is technology selection and solution planning. It probably includes the following two points:

  1. The most basic technical solution

  2. Development process and specifications

Technical solution selection

Webpack + React + Sass

Since the team’s existing projects are all developed based on React+Redux, we chose The development language is undoubtedly React.

SASS

For css selection, although now for component development, CSS Modules and CSS-IN-JS are more popular modular solutions, we prefer Our components are customizable. Therefore, for components, we use Sass as a precompiled language to improve efficiency and standardization. With css-modules, we can easily make style changes based on actual needs. For example, we have a Tab component, and we have defined its general style:


.tip-tab {
 border: 1px solid #ccc;
}
.tip-tab-item {
 border: 1px solid #ccc;
 
 &.active {
  border-color: red;
 }
}
Copy after login

In business, for a certain requirement, we need to style the Tab component Make fine adjustments. Let the border-color be blue in the active state. Of course you can say that we can let our components expose some props, configure them for these modifications, and pass in different props corresponding to different styles. However, we often cannot meet all business needs, and it is impossible to encapsulate various styles for components. For this solution, we use css-modules to add a unique module style:


<Tab styleName="unique-tab" />
Copy after login

For this module, modify the basic style:


.unique-tab {
 :global {
   .tip-tab-item {
    border-color: #eee;
    
    &.active {
     border-color: blue;
    }
   }
 }
}
Copy after login

In this way, the customized style of this module can be customized to meet the needs without polluting the global style.

Icon

For the project icon, it is planned to use the svg-sprite solution. However, because the product is in the process of continuous iteration, new icons are constantly being added. Currently, we do not package icons uniformly. Instead, we import all icons from the project during each component packaging process. Use the following method to introduce:


import Icon from &#39;@common/lib&#39;
import errorIcon from &#39;@images/error.svg&#39;

<Icon link={errorIcon} />
Copy after login

In fact, a better way is to package all icons uniformly and generate svg-spirte files (for specific principles, you can query svg-sprite, I won’t go into details here). When we use it, we only need to quote it directly to avoid packaging every time and reduce the time webpack takes to process dependencies:


<Icon type="error" />
Copy after login

Development process and specifications

Regarding the development process and specifications, we follow the following principles:

  1. The component library is completely independent of the project to develop, which facilitates subsequent multiple Project use, etc.

  2. The component library contains three modes: development, testing, packaging, and document cases, distinguishing different entrances and states

  3. Use pure-renderautobind, etc. to ensure the performance and efficiency of components as much as possible

  4. Ensure the semantics of props and callbacks. For example, callbacks are processed uniformly using handleXXX

In order to facilitate subsequent expansion, we prefer that the entire component library be developed completely separate from the project. Ensure that the component library only encapsulates the most basic components and separates the project UI code from business logic.

针对不同的模式下,我们有不同的文件入口,针对开发模式,我们启动一个dev-server, 在里面对组件进行基本的封装,并进行调试。打包时,我们只需对组件内容进行封装,暴露统一的接口。在文档中,我们需要进行案例和说明的展示。所以我们在利用webpack的特性进行各种环境的配置:


npm run dev // 开发
npm run test // 测试
npm run build // 构建
npm run styleguide // 文档开发
npm run styleguide:build // 文档打包
Copy after login

组件库作为项目的最小力度支持,我们需要保证其最基本的渲染效率,因此我们采用pure-render/autobind等对其进行基本的优化。React有很多优化方式,在此不进行赘述。

打包

基础

针对组件库的打包,我们以UMD格式对其进行打包。webpack可以针对输出进行格式设置:(引自cnode)

  1. “var” 以变量方式输出

  2. “this” 以 this 的一个属性输出: this[“Library”] = xxx;

  3. “commonjs” 以 exports 的一个属性输出:exports[“Library”] = xxx;

  4. “commonjs2” 以 module.exports 形式输出:module.exports = xxx;

  5. “amd” 以 AMD 格式输出;

  6. “umd” 同时以 AMD、CommonJS2 和全局属性形式输出。

配置如下:


output: {
 path: config.build.assetsRoot,
 filename: utils.assetsPath(&#39;js/[name].js&#39;),
 chunkFilename: utils.assetsPath(&#39;js/[id].js&#39;),
 library: &#39;TipUi&#39;,
 libraryTarget: &#39;umd&#39;
}
Copy after login

依赖

很明显,我们封装的是一个针对React的组件库,并不应该把React引用进去。一般我们可以采用externals的方式对其进行处理。

在这里, 我们采用dll方式将其与其他第三方依赖统一进行打包,并将manifest.json和三方依赖的输出文件输出到项目中去,在项目中也使用dllReference进行引用。避免在项目中使用到这些依赖时重复进行打包。

同时,由于我们的组件库处于一个不断维护的状态。这就需要我们维持好项目库和项目之间的打包关系,具体的流程如图所示:

在每次进行项目打包的时候,首先检测UI库是否有更新,若没有更新,则直接进行打包。反之继续检测dll的依赖是否有变化,若有,则打包dll,否则直接打包组件库内容。然后将输出结果同步到项目中,再进行最终打包。

当然,以上的这些流程都是自动进行的。

文档和示例

一个完善的文档对于一个组件库是及其重要的,每个组件有什么样的配置参数,拥有哪些事件回调,对应的Demo和展示效果。假设没有这些,除了封装组件的人,没有人知道它该如何使用。但是写文档的过程往往是痛苦的,在这里推荐几个文档生成库,可以极大的简化文档工作:

docsify 基于Vue的组件生成器,轻量好用
react-styleguidist 基于React的组件库文档生成器,自动根据注释生成文档,支持Demo展示。超好用
bisheng ant design自己写的文档生成器

我们使用的styleguidist, 可以将md自动转化为文档,支持在md内直接调用你封装好的组件并进行展示,简单好用。最后封装的文档大概长这样:

总结

其实封装组件库这种工作有很多的东西值得琢磨和钻研,由于篇幅原因,在这里只对开发过程中比较纠结的选型和打包等进行讨论,后续再对具体组件的封装进行讨论。在书写的同时,不断参考下ant design这种优秀的组件库,能学到很多的东西。更深刻的理解封装组件的思想,是一个很好的过程。

相关推荐:

MintUI基于Vue.js移动端组件库详解

The above is the detailed content of Examples of component library development using React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Which Linux distribution is best for Android development? Which Linux distribution is best for Android development? Mar 14, 2024 pm 12:30 PM

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

&quot;Understanding VSCode: What is this tool used for?&quot; 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

See all articles