Home > Web Front-end > Vue.js > body text

Teach you step by step how to build a UI component library from scratch

藏色散人
Release: 2023-04-13 17:42:21
forward
2983 people have browsed it

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.

Teach you step by step how to build a UI component library from scratch

1. Environment preparation

Before we write the components of our component library, we first need an environment, including the following items:

  1. Need to create a new project separately for the component library
  2. Need to plan a suitable directory structure
  3. Need to define the writing of component documents
  4. 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
Copy after login

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'

  }

}
Copy after login

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.

vue-markdown-loader

##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
Copy after login

1.3.2 webpack configuration

We 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()]
Copy after login

1.3.3 Writing component documents

After 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 world
Copy after login

Next 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 docs
Copy after login

Run in the browser, we can see the first component document of our component library...

The above is completed, our component library The environment is basically set up. Next, we try to start writing a new component.

  1. Component creation

We start with a basic button component.

First we add the following structure to the previously created packages:

    sg-button component directory
  • index. js component installation entry program
  • src component source code
2.1 component vue source code

Here I simply implemented a button component in src/index.vue, supporting Buttons of three sizes,





Copy after login

2.2 Component export

Then 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 sgButton
Copy after login

Then 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

}
Copy after login

2.3 Component introduction

Introduce on demand:

import sgUi from '../packages/index'



Vue.use(sgUi.sgButton)
Copy after login

Introduce all:

import sgUi from '../packages/index'



Vue.use(sgUi)
Copy after login

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: ''

})
Copy after login

然后我们编写一个vue页面来看看是否引入成功。

首先examples中新增pages目录,存放我们以后为每个组件单独编写的示例页面,新增examples/pages/buttonExample/index.vue 页面



Copy after login

在这里我们直接调用了三种尺寸的button,运行看下效果:

效果完美,代表我们组件库第一个组件以及整体流程打通!

  1. 组件库发布

之前的环节,我们成功实现了我们组件库的第一个组件,但考虑到这只是组件库,组件库内能调用肯定是不够的,类似 vant/ant 这些组件库,我们怎么让其他用户可以使用我们的组件库组件内?

我们可以考虑发布到npm上,后续项目需要的话,我们直接通过npm安装引入的方式来调用。

发布到npm的方法也很简单, 首先我们需要先注册去npm官网注册一个账号, 然后控制台登录即可,最后我们执行npm publish即可.具体流程如下:

// 本地编译组件库代码

yarn lib

// 登录

 npm login

 // 发布

 npm publish

 // 如果发布失败提示权限问题,请执行以下命令

 npm publish --access public
Copy after login
  1. 单元测试

Vue Test Utils 安装

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!

Related labels:
source:juejin.im
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!