preface

As data-driven Web frameworks like VUE/React continue to improve and grow, more and more front-end teams are starting to build in-house component libraries. At present, there are many powerful and complete component libraries for us to use in the market, such as the react-based open source component library Ant-Design, Material, and vUe-based open source component library elementUI, iView, etc.

When we develop management systems or middle platform products, we can fully use such third-party libraries for development. Firstly, the user groups it serves are relatively small, usually used by enterprises or operation personnel. The focus is on functions and businesses, so b-side products are more suitable. The other point is that the design requirements are lower than c-end products, because the unified and simple style of B-end products or management systems will reduce the learning cost of users. In this case, we can use an integrated management framework like Ant-Design-Pro or Element-admin-Vue.

We use third-party component libraries to build an enterprise application is completely no problem, but on the other hand, as we are increasingly demanding on the properties of user experience and site, traffic and money, speed is king, for focus on doing the enterprise C, as far as possible to reduce the user waiting to retain more users, such as we are a treasure, Some east to buy a product, the result we spend a minute the list of goods has not come out (describe a little exaggeration), in this case the customer may directly choose a spell. Obviously components like Ant-Design and elementUI are not suitable for c-side products because they are too large, unless compensated for by high performance servers or other means. So there are several benefits to adopting a lightweight component library for a C-side project:

  • Small packaging volume, highly controllable
  • The internal component library provides higher security and prevents embedding attacks
  • Construction and development is more flexible, and the combination is higher

But developing component libraries takes time and cost, and it’s not something every team can play with. With that said, it’s time to analyze and implement a team’s internal component library.

You will reap

  • How do I build a component library from 0
  • Design idea and pattern of front-end component system
  • Component library division and design ideas
  • Configuration instructions for the package.json file of the component library
  • Deploy the component library to Github and publish it to NPM

The body of the

1. Several ways to develop component libraries

  • Front-end component/library packaging sharp Rollup use and configuration combat
  • Package and compile your own third-party UI component library based on create-React-app and publish it to NPM
  • Jquery, React, vue, typescript

The fastest way to do this is to go directly to ant-Design or elementUI’s Github repository and copy the code and use it as your own component library scaffold. Of course, it’s not easy to do this, but if you want to try this solution, you should learn typescript and Webpack first.

The author here uses the current popular tool chain UMI, UMI father is specialized in providing component libraries or tool library package integration tools, we only need to change the configuration file can easily build a built-in description of the component library. Here’s how to use it.

2. Front-end component system design ideas and patterns

For any complex system, the most important thing is to realize the complex business functions, but is often a lot of business between different modules or subsystems is same or similar, if this time we each page similar to implement the business scenario to repeat to write again business code, that is completely unnecessary, for maintainability is also a kind of attack, This is where our business components come in. We can encapsulate an organism with similar functionality or requirements as a business component and expose interfaces to achieve flexible customisability so that we can reuse the same logic and functionality across different subsystems on different pages.

Similarly, different pages may have identical or similar blocks visually or interactively. In order to improve reusability and improve development efficiency, we tend to repackage the underlying components and business components into a separate block for direct reuse.

Through these layers of encapsulation, we gradually build a complete set of componentized system, and development based on this pattern is often the beginning of a good front-end architecture. It is important to note that higher-level components must depend on lower-level components, but lower-level components cannot contain higher-level components. (Sounds a bit like Rudex’s unidirectional data flow), and their relationship looks like this:

3. Division and design of component library

The division of component libraries can refer to the division of mature component libraries. Since business component and block division is completely dependent on the actual project situation of different companies, there is no unified framework of thinking, so I refer to component library division here mainly to the basic component library division. Let’s take a look at the division of ANTD, which is divided into general purpose components, layout components, navigation components, data entry and data presentation components, feedback components, and others. The components of elementUI are divided into basic components, form components, data rendering components, notification components, navigation components and others. These categories are very reasonable, so we can refer to or directly use them when designing component libraries. The specific summary is as follows:

  • Generic components: Button, Icon, etc.
  • Layout components: Grid, Layout, etc.
  • Navigation components: Breadcrumb, Dropdown, Menu, etc.
  • Data entry components: such as form, Switch, Upload file Upload, etc.
  • Data presentation components: Avator profile, Table, List, etc.
  • Feedback components: Progress bars, drawers, Modal dialog boxes, etc.
  • Other Business Types

As for the design idea of component implementation, in fact, the author has written many articles before to pave the way, the first important point is requirements, everything should start from requirements. Not only react component design, vUE or Angular are similar methods and ideas, here simply give you an example of component development — Modal components (Modal) development ideas:

  1. Demand analysis
  2. Functional design and implementation ideas
  3. Robustness and component testing

    Since Modal design is a typical example of component design, you can do so after reading this article if you want to learn the implementation detailsHand to Hand implements a lightweight and extensible Modal component

4. Build a component library from 0

This step is the focus of this article, where we will learn how to use UMI/Father to build a team’s component library. As for UMI, the front-end integration solution, the author has been inspired by its architecture, and the front-end development process based on UMI + DVA + React is widely used, so interested friends can study and learn about it.

4.1 father introduced

Library packaging tool based on Rollup and Docz. Its main features are:

  • Docz-based documentation capabilities
  • Component packaging based on Rollup and Babel
  • Support the TypeScript
  • Supports CJS, ESM, and UMD packaging
  • The ESM supports generating MJS directly for use by browsers
  • Support for packaging CJS and ESM in Babel or Rollup
  • Support for multiple entry
  • Support lerna
  • Supports CSS and LESS, and supports enabling CSS modules
  • Support the test
  • You can use prettier and ESLint to perform pre-commit checks

So packed as a component library out-of-the-box tool, has been for us to save a lot of intermediate steps, such as component testing, module packaging under different environment, but also support ts and function of the document, we only need to master the knowledge of Babel and rollup, can use it to easily configure a powerful component library of scaffolding. If you don’t know much about Docz, you can learn to use docz website is very easy, as long as you are familiar with Markdown and React, it will be easy to get started.

4.2 Using Father to Build a Component Library

In fact, the use of father is very simple. First, let’s install father:

npm install father -D
Copy the code

Or use YARN to install:

yarn add father
Copy the code

Next we can configure the following script in package.json to use:

$father doc dev $father doc build $father doc dev $father doc build $father doc deploy # Component library tests and test coverage $father test $father test --coverageCopy the code

Take for example xuI, a lightweight UI component library based on React that I have previously published to NPM. First let’s look at how the xui package.json script is configured:

"scripts": {
    "dev": "npx --max_old_space_size=8096 father doc dev --host 0.0.0.0"."build": "father build"."build:doc": "father doc build"."deploy": "father doc deploy"
  }
Copy the code

When we run NPM run dev or yarn dev, father automatically starts the doc server for us and we can see the test documentation for our component:

---
name: Button
route: /Button
order: 3
sidebar: true
---

import { Playground } from 'docz'
import Button from './index'

# Button

#### Basic usage
<Playground>








</Playground> Copy the code

Header information I need to introduce:

  • Name Specifies the name of the component, which is the navigation text displayed in the left navigation bar
  • Route Indicates the route on the component page
  • Order The order in which components are displayed in the navigation bar
  • Siderbar Whether the navigation bar is displayed on the current page

According to the case, we can know that MDX can use ES6 import to introduce components or variables, in fact, there are a lot of configuration, here is not an example, interested in the docz official website to learn. Here is a screenshot from the official website:

.fatherrc.js
xui

// .fatherrc.js
const options = {
  entry: 'src/index.js'.doc: {
    title: 'xu_ui'.themeConfig: { mode: 'light' },
    base: '/xu_ui'
  },
  extraBabelPlugins: [['babel-plugin-import', {
          libraryName: 'antd'.libraryDirectory: 'es'.style: true,}]],// cssModules: true,
  extractCSS: true.lessInBabelMode: true.runtimeHelpers: true.esm: 'babel'.cjs: 'babel'.autoprefixer: {
      browsers: ['ie>9'.'Safari >= 6']}};export default options;
Copy the code
  • entryThis is used to define the entry location of the component library, usually in the SRC directory. Here is the SRC directory structure of the XUI project:

    You can refer to the following, we can also add test code in the component directory, here is not an example.

  • The doc is used to configure the title, subject color, and root routing of the document
  • ExtraBabelPlugins are used to configure additional Babel plugins, such as the on-demand import of component libraries. Although ANTD is not used in XUI, if you have secondary development business components or blocks based on ANTD, you can import third-party component libraries as required according to the above configuration, which can greatly reduce the code volume
  • CssModules whether to enable the CSS Module, which can be customized according to the team’s needs and may not be configured
  • ExtractCSS whether to pull out the CSS into a separate CSS file, this is also to see the volume of the component library, but it is recommended that the best configuration
  • LessInBabelMode Compiling is performed in Babel mode. This function is disabled by default based on gulp-less
  • RuntimeHelpers can use helper methods in @babel/ Runtime to save a lot of code
  • Whether the ESM outputs the ESM format and how to package the ESM format are specified. The author uses Babel packaging here
  • CJS output CJS format, and specify the CJS format packaging, etc., the author here use Babel packaging
  • Autoprefixer is used to configure the browser compatible versions of packaged components

With the above configuration, we can happily develop components.

4.3 Writing Component Description Documents

The component documentation is the key to letting others know about the library, including the scope of the library (PC, mobile, lightweight or heavyweight), the browser version, the design principles and background, the community ecology, how to use it, and so on. So the component library documentation is also very important, you can refer to the ANTD or Element documentation, can be said to be written very professional. Here is an example of ANTD:

5. Configuration description of the package.json file of the component library

If you’re developing a private component library for your team, you don’t need to worry about what I write next, but if you’re developing an open source component library that everyone can use, here are a few things to write about:

  • What is the name of the library for
  • A precise and specific description of the component library is helpful for people to search on NPM or Github. It has a similar feel to SEO. Yes, this is SEO
  • Keywords component library keyword description, which is also important, directly influences user search rankings for our component library
  • Xui, a lightweight UI component library based on React, is a complete online example

6. Deploy the component library on Github and publish it to NPM

First we need to configure the github address in package.json:

"repository": {
    "type": "git"."url": "git+https://github.com:MrXujiang/xu_ui.git"
  }
Copy the code

You can copy the above code to change your own warehouse address.

Secondly, we need to log in to the official website of NPM. If you do not have an account, you can directly apply for one, which is very simple, and then log in through the command line in the terminal.

To package our component libraries to NPM, run the following commands:

// Package and compile the component library
yarn build

// Compile the component library documentation. This step can be omitted
yarn build:doc

// Deploy the component library documentation to Github. This step can be omitted
yarn deploy

// Publish to NPM
npm publish --access public
Copy the code

For details about the above yarn commands, see the package.json of XUI, or you can configure the yarn commands yourself. After the above steps, we successfully publish our component library to NPM, is it easy?

I have published the implemented components to NPM. If you are interested, you can directly use NPM after installation. The method is as follows:

npm i @alex_xu/xui

/ / import xui
import { 
  Button, Skeleton, Empty, Progress,
  Message, Tag, Switch, Drawer, Badge, Alert
} from '@alex_xu/xui'
Copy the code

This component library can be imported on demand. We only need to configure babel-plugin-import in the project. The specific configuration is as follows:

// .babelrc
"plugins": [["import", { "libraryName": "@alex_xu/xui"."style": true}]]Copy the code

The NPM library screenshot is as follows:

Preliminary study on component system and micro front-end architecture

This article will not cover the knowledge of micro front-end architecture, but since the component library is involved, a knowledge loop must be formed. The author intentionally drew the following brain map for front-end friends or teams who are going to micro front-end architecture for reference:

The last

If you are not familiar with react/ Vue component design principles, please refer to my previous component design series:

  • Master React/Vue family to implement a global Message component
  • Realize a powerful Notification box with the React/Vue Series.
  • Hand to Hand implements a lightweight and extensible Modal component
  • Master React/Vue Component Design implements a powerful Drawer component in conjunction with React Portals
  • Implement a Tag component and an Empty component in 5 minutes of React/Vue Component Design Mastery
  • Master React/Vue Component Design creates materialui-like button click animations with pure CSS and encapsulates react components
  • Quickly implement a customizable progress bar component in Master React/Vue Component Design
  • Master React/Vue Component Design: Repackaging a real-time preview JSON editor component in JsonEditor (React version)

I have published the component library on NPM, and you can experience the components through the NPM installation.

If you are vUE technology stack, I still strongly recommend the use of VUE – CLI to build the component library, as to how to build vUE component library, I have time later will be a detailed article to introduce.

If you want to get the complete source code of component design series, or want to learn more H5 games, Webpack, node, gulp, CSS3, javascript, nodeJS, Canvas data visualization and other front-end knowledge and practical, welcome to join our technical group in the public number “interesting talk front end” to learn and discuss together, Explore the boundaries of the front end together.

More recommended

  • 2 years of vUE project practical experience summary
  • Javascript Design Patterns front-end Engineers Need to Know in 15 minutes (with detailed mind maps and source code)
  • In 2019, take a look at some of my top questions and advice for job seekers
  • A picture shows you how to play vue-Cli3 quickly
  • Vue Advanced Advanced series – Play with Vue and vuex in typescript
  • “Front-end combat summary” the use of pure CSS website skin and focus diagram switch animation
  • “Front-end combat summary” using CSS3 to achieve cool 3D rotation perspective
  • Add a loading progress bar to your site using pace. Js
  • The Application of design Pattern of “Summary of Front End Actual Combat” — Memorandum Pattern
  • “Front End Combat Summary” using postMessage to achieve pluggable cross-domain chatbot
  • “Front-end combat summary” of the variable promotion, function declaration promotion and variable scope detailed explanation
  • “Front-end combat summary” how to change the URL without refreshing the page