Writing in the front

Little heads with big dreams. Making a UI component library of our own would be a good little goal. That… What is the component 😯? I think it goes without saying that every vUE you write can be treated as a component, with a difference in versatility, as we work with it on a daily basis. As you write more components, over time you will be tempted to write a library of components. In fact, it is more to improve the B box 😢, when talking to people, you say you have written a UI library, people think you may be a bit of a nerd. Good, do not blow B, hurriedly wanke 😜

Source address: github.com/lgq627628/x…

Knowledge of pre –

We may be used to importing components within a VUE, so let’s consolidate the global importing method here. For example, 🌰 is used like this:

import Loading from '.. /components/loading'
// Method 1: name is the name of the component
Vue.component(Loading.name, Loading)
// If Loading does provide the install method
Vue.use(Loading);
Copy the code

Both of the above methods can be used to register components globally, but the parameters are different. Choose either method, but keep an eye on the second method, which requires the component itself to have an install method. Er… Why is there a install method? Just think of it as a rule, and if you use someone else’s framework, you have to follow their rules. Tear came 🐂, because actually perform the Vue. Use inside will perform the install method, so we need to write an install. This you need not take seriously, the dependence is such, oh no 🙅♀️, should be standing on the shoulder of god 💪.

Build directory

Creating a project quickly

This step should go without saying, just execute vue Create XR-UI (assuming you have vue-cli3 installed), select a few configurations to your liking, and with a few hits of the press enter, you have a neat initial project. I didn’t choose to use typescript here (mainly because I’m not used to it yet), so for those of you who choose typescript, it might be written a little differently.

Modifying the directory structure

  1. Change the SRC directory name to examples, which is used to show examples of components
  2. Create a new packages folder in the root directory where you can put your components

You may be asking why we have such a directory structure. Good question. The reason is simple, because others do. We can see that the source code for Element has the same structure:

When our level is not enough, imitation is a powerful learning ability 👏.

Adding a Configuration File

After a few directory changes, you may be surprised to find that the project doesn’t work. It doesn’t matter, this is normal, after all, the SRC is gone, and the path is going to be wrong. So now let’s solve this problem. Create a new vue.config.js file in the root directory (the new project does not have this file) and write the following:

const path = require('path')
module.exports = {
  // Modify the Pages entry
  pages: {
    index: {
      entry: 'examples/main.js'./ / the entry
      template: 'public/index.html'./ / template
      filename: 'index.html' // Output file}},// Extend webPack configuration
  chainWebpack: config= > {
    // @points to the SRC directory by default
    // You can also add a new ~ point to packages
    config.resolve.alias
      .set(The '@', path.resolve('examples'))
      .set('~', path.resolve('packages'))

    // Add packages and examples to the compilation because new files are not processed by WebPack by default
    config.module
      .rule('js')
      .include.add(/packages/).end()
      .include.add(/examples/).end()
      .use('babel')
      .loader('babel-loader')
      .tap(options= > {
        // Modify its options...
        return options
      })
  }
}
Copy the code

The comments above should be clear, mainly the steps of changing the alias, modifying the entry file, and adding the new file to the WebPack compilation. And then we’ll run the program and it’ll work. As for why and how to configure it, those who do not know about it can go to the official website of Vue Cli, which is clear and clear. However, I only understand one or two configurations 😭😭😭. I have not learned the routine of Webpack, because I often look at it when I use it, and then forget it when I do not use it for a while. No way 🤷♀️ no brain.

Write a component

A component library can’t do without components, so we’ll write a test component first (you can write whatever you want, it doesn’t matter). Ok 👌, create a new test folder under test. Create a new SRC folder under test. Create a test.

<! --test.vue-->
<template>
  <div class="xr-test" @click="handleClick">{{ num }}</div>
</template>

<script>
export default {
  name: 'XrTest'.
       
  data () {
    return {
      num: 0}},methods: {
    handleClick () {
      this.num++
    }
  }
}
</script>

<style lang="scss" scoped>
.xr-test {
  width: 100px;
  height: 100px;
  line-height: 100px;
  border-radius: 50%;
  font-size: 30px;
  text-align: center;
  background: #24292e;
  color: white;
}
</style>
Copy the code

I think you can understand it, but I don’t want to explain it. ⚠️ The main point here is that the name is particularly important, I have been in this pit for a long time. First of all, it must be written. Why? You can think of it as an ID that uniquely identifies a component. In the future, we will use this name to find and determine what component it is. Next, the name will be our final tag name. For example, in this case, the name will be XrTest, and then the tag will look like
, just like Element, and the name will be ElButton,

Exposure of the component

Let’s create an index.js file under packages/test.

// Provide an install method for components to be imported as needed
import XrTest from './src/test'
XrTest.install = Vue= > {
  Vue.component(XrTest.name, XrTest)
}
export default XrTest
Copy the code

The essence of this step is to extend the install method to the component. The reason for extending this method, as explained at the beginning of this article, is because of the need for vue.use (), which by default calls the install method, and that’s it. Select * from index.js where index.js is installed for individual components. Select * from index.js where index.js is installed globally for all components.

import XrTest from './test'
// List of all components
const components = [
  XrTest
]
// Define the install method to accept Vue as an argument
const install = function (Vue) {
  // Check whether it is installed. If it is installed, do not continue to execute
  if (install.installed) return
  install.installed = true
  // Iterate over all registered components
  components.map(component= > Vue.component(component.name, component))
  // You can also write it this way
  // components.map(component => Vue.use(component))
}

// Execute only when Vue is detected. After all, we are based on Vue
if (typeof window! = ='undefined' && window.Vue) {
  install(window.Vue)
}

export default {
  install,
  // All components must have install in order to use vue.use (). components }Copy the code

The main purpose of this step is to export all components uniformly and expose the install method. Whereas index.js previously installed a single component, this index.js installs all components in a loop, depending on whether you need to refer to them as needed. Here’s a directory structure for you to see:Since this is an important step, it is advisable to stop and digest it 🤔…

Now, of course, you might ask, why do we do this? Why else? Because Element is like this, so we write it like this, that’s all.

Component test

Ok, that’s it. Let’s test it under examples and see if it works. First, introduce the just written package in main.js under examples, as follows:Then delete the contents of home.vue under examples/views and write it to your own tag component like this:Ok, let’s run the project finallyyarn serveLook at the effect, well, not bad.

Library pattern packaging

In vue-cli3 we can package a single entry into a library with the following command:

// target: the default is build application. Change to lib to enable build library mode
// name: output file name
// dest: the output directory, which defaults to dist. Here we change it to lib
// entry: entry file path
vue-cli-service build --target lib --name lib [entry]
Copy the code

Note that in the library pattern, Vue is not included in the packaged library. Then we modify the package.json file to look like this:Then performnpm run libLet’s see if there’s a lib folder in the left directory. That’s what we’re going to publish.In addition, there are several types of JS in the lib directory, because there are two different specifications (common and UMD), whether compression (min) and map (Map), so you don’t need to go into the details.

Published to the NPM

All we need is a release.

  1. To perfect the readme.md document, just write a few sentences about this
  2. Modify the package.json file:
{ 
  "name": "xr-ui"."version": "0.3.0"."description": "UI Component library based on Vue-CLI3"."main": "lib/xr-ui.umd.min.js".// This is one of the files in the lib directory
  "keywords": "xr-ui"."private": false."license": "MIT"
}
Copy the code
  1. Create a new.npmIgnore file in the root directory, similar to.gitignore:
# local env files.env.local.env.*. Local # Log files npm-debug.log* yarn-debug.log* yarn-error.log* # Editor directories and files .idea .vscode *.suo *.ntvs* *.njsproj *.sln *.sw* # # to ignore directories and specify examples/ packages/ public/ vue.config.js babel.config.js *.map *.htmlCopy the code

Finally, run the NPM login command to login to the NPM account, and then run the NPM publish command. Of course, the prerequisite is that you have an NPM account, if not, register one, very easy, and then search for your NPM package name is used, if there is another.

A profound

Finally, after all the hard work, we can quote our own Kula, which is great to think about. Take it easy. Let’s try it outvue create newStart a new project, and thennpm i xr-ui -SYou can see in node_modules that our package looks something like this:Then in main.js introduce:

import Vue from "vue"
import XrUI from 'xr-ui'
import 'xr-ui/lib/xr-ui.css'

Vue.use(XrUI)
Copy the code

So we can introduce components into the page, haha, happy, happy…

<xr-test></xr-test>
Copy the code

summary

Think about how great it would be if you maintained a component library for your team. Of course, a good memory is not as good as a bad keyboard, read does not mean to master, only their own experience is really unforgettable, 😓. What a sudden lyric. Finally, I would like to emphasize that imitation is a necessary skill when the level is not enough, like me. But it doesn’t matter, this is just a process, when you write code for a few years, there will always be some ideas of their own, and then can slowly precipitation out of some of their own things, we just stand on the shoulders of giants to move forward, that’s all, see 👋👋👋