Teach you step by step how to build a UI component library from scratch
This article brings you relevant knowledge about UI components. It mainly talks about how to build a UI component library from scratch. There are code examples. Friends who are interested can take a look below. I hope everyone has to help.
1. Environment preparation
Before we write the components of our component library, we first need an environment, including the following items:
- Need to create a new project separately for the component library
- Need to plan a suitable directory structure
- Need to define the writing of component documents
- Need to build Complete unit testing
1.1 Project construction
Our current project is based on the vue2 version, so this component library project will also be created using the vue cli version 2.0.
// 全局安装 vue-cli npm install --global vue-cli // 基于 webpack 创建一个的新项目 vue init webpack my-project // 安装依赖 npm install // 运行 npm run dev
The relevant options during the installation process are as follows:
We install jest by default as the unit testing framework for our component library, and the code inspection tool defaults to eslint
1.2 Directory Optimization
After successfully creating the project, the directory structure of our new project should now be like this:
- build package related directories and configuration
- config configuration file directory
- node_modules Dependent modules installed in the project
- src source code directory
- static static file directory
- test unit test directory
We need to Make some adjustments to the existing directory. First of all, we have come into contact with some mainstream UI component libraries such as vant/ant. We know that the official websites of these component libraries provide very intuitive sample pages. At this time, our component library will rename the src directory. for examples, as our official examples directory.
In addition, we add a new packages directory to store our components.
Now our directory structure becomes as follows:
#If you rerun the project at this time, you will find an error, because our src directory name has changed, and the webpack configuration The default entry file is still src/main.js. We need to change the configuration and replace src with examples in the build/webpack.base.conf file. At the same time, we need to add the new packages directory to the webpack compilation queue.
The changed webpack.base.conf should look like this.
'use strict' const path = require('path') const utils = require('./utils') const config = require('../config') const vueLoaderConfig = require('./vue-loader.conf') function resolve (dir) { return path.join(__dirname, '..', dir) } const createLintingRule = () => ({ test: /.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', include: [resolve('examples'), resolve('packages'),resolve('test')], options: { formatter: require('eslint-friendly-formatter'), emitWarning: !config.dev.showEslintErrorsInOverlay } }) module.exports = { context: path.resolve(__dirname, '../'), entry: { app: './examples/main.js' // 打包入口 }, output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('examples'), } }, module: { rules: [ ...(config.dev.useEslint ? [createLintingRule()] : []), { test: /.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /.js$/, loader: 'babel-loader', include: [resolve('examples'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] }, { test: /.(png|jpe?g|gif|svg)(?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { test: /.(mp4|webm|ogg|mp3|wav|flac|aac)(?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('media/[name].[hash:7].[ext]') } }, { test: /.(woff2?|eot|ttf|otf)(?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] }, node: { // prevent webpack from injecting useless setImmediate polyfill because Vue // source contains it (although only uses it if it's native). setImmediate: false, // prevent webpack from injecting mocks to Node native modules // that does not make sense for the client dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty' } }
Rerun and the compilation passes.
1.3 Writing component documents
After setting up the basic coding environment, we need to consider how to write the component documentation for our new components.
We recommend using markdown to write component documents. Then how do we use markdown to write our component documents in vue? Here we recommend a useful tool.
##1.3.1 Installation method# vue1版本
npm i vue-markdown-loader@0 -D
# vue2版本
npm i vue-markdown-loader -D
npm i vue-loader vue-template-compiler -D
1.3.2 webpack configurationWe are making the following modifications to webpack.base.conf: const VueLoaderPlugin = require('vue-loader/lib/plugin'); module: { rules: [ ..., { test: /.md$/, use: [ { loader: 'vue-loader' }, { loader: 'vue-markdown-loader/lib/markdown-compiler', options: { raw: true } } ] }, ... ] }, plugins: [new VueLoaderPlugin()]1.3.3 Writing component documentsAfter we configure the tools, we start to test the writing of component documents,First, we add a docs folder in the examples directory to store our component documentation. Create a new test.md
# hello worldNext we add a docs.js routing file in the router folder to store the path of our component documentation and introduce it to the root route in the file.
const docs = [ { path: '/test', name: 'test', component: r => require.ensure([], () => r(require('../docs/test.md'))) } ] export default docsRun in the browser, we can see the first component document of our component library...
- Component creation
- sg-button component directory
- index. js component installation entry program
- src component source code
<template> <div :class="[size]" @click="click()"> <span><slot></slot></span> </div> </template> <script> /** * 全局统一弹窗 */ export default { name: 'sgButton', props: { size: { type: String, default: '' } // 按钮大小 :small large }, methods: { click () { this.$emit('click') } } } </script> <style scoped> .container{ height: 50px; display: flex; justify-content: center; align-items: center; border: 1px solid #ccc; } .container.small{ height: 40px; } .container.large{ height: 60px; } </style>2.2 Component exportThen how do we use this component? We are considering a component library, so we need to make our components support global import and on-demand import. If imported globally, then all components need to be registered on the Vue component and exported: We need to add the following code to the component's entry file index.js:
// 导入组件,组件必须声明 name import sgButton from './src' // 为组件提供 install 安装方法,供按需引入 sgButton.install = function (Vue) { Vue.component(sgButton.name, sgButton) } // 导出组件 export default sgButtonThen we add a new entry file in the packages directory to process and export all components in a unified manner:
// 导入button组件 import sgButton from './sg-button' // 组件列表 const components = [ sgButton ] // 定义 install 方法,接收 Vue 作为参数。如果使用 use 注册插件,那么所有的组件都会被注册 const install = function (Vue) { // 判断是否安装 if (install.installed) return // 遍历注册全局组件 components.map(component => Vue.component(component.name, component)) } // 判断是否是直接引入文件 if (typeof window !== 'undefined' && window.Vue) { install(window.Vue) } export default { // 导出的对象必须具有 install,才能被 Vue.use() 方法安装 install, // 以下是具体的组件列表 sgButton }2.3 Component introduction Introduce on demand:
import sgUi from '../packages/index' Vue.use(sgUi.sgButton)Introduce all:
import sgUi from '../packages/index' Vue.use(sgUi)
2.4 测试代码
我们在examples目录的入口文件中全局引入了组件库
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import sgUi from '../packages/index' Vue.config.productionTip = false Vue.use(sgUi) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
然后我们编写一个vue页面来看看是否引入成功。
首先examples中新增pages目录,存放我们以后为每个组件单独编写的示例页面,新增examples/pages/buttonExample/index.vue 页面
<template> <div class="container"> <sg-button>默认按钮</sg-button> <sg-button :size="'large'">大按钮</sg-button> <sg-button :size="'small'">小按钮</sg-button> </div> </template> <script> /** * button 示例 */ export default { name: 'buttonExample', methods: { } } </script>
在这里我们直接调用了三种尺寸的button,运行看下效果:
效果完美,代表我们组件库第一个组件以及整体流程打通!
组件库发布
之前的环节,我们成功实现了我们组件库的第一个组件,但考虑到这只是组件库,组件库内能调用肯定是不够的,类似 vant/ant 这些组件库,我们怎么让其他用户可以使用我们的组件库组件内?
我们可以考虑发布到npm上,后续项目需要的话,我们直接通过npm安装引入的方式来调用。
发布到npm的方法也很简单, 首先我们需要先注册去npm官网注册一个账号, 然后控制台登录即可,最后我们执行npm publish即可.具体流程如下:
// 本地编译组件库代码 yarn lib // 登录 npm login // 发布 npm publish // 如果发布失败提示权限问题,请执行以下命令 npm publish --access public
单元测试
The above is the detailed content of Teach you step by step how to build a UI component library from scratch. For more information, please follow other related articles on the PHP Chinese website!

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.