Home Web Front-end Vue.js How to create a Vue component library from scratch and publish it to npm

How to create a Vue component library from scratch and publish it to npm

Jan 13, 2022 pm 06:38 PM
vue component

How to create a Vue component library from scratch and publish it to npm? The following article will guide you step by step in developing a Vue component library from scratch and see how to publish it to npm. I hope it will be helpful to you.

How to create a Vue component library from scratch and publish it to npm

1. Create a new folder, open it in the terminal and execute npm init -y

Generate package.json as follows. Note that if you want to publish it to npm, the name cannot have underscores, capital letters, etc.

{
  "name": "vuecomponentdi",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
Copy after login

2. Create a directory structure

The directory structure is as follows

-- vueComponentDi
    -- packages
        -- button
            -- index.js
            -- index.vue
        -- toast
            -- index.js
            -- index.vue
    -- index.js
    -- package.json
Copy after login

3. Local debugging

  • vueComponentDi/index.js
export default function(){
    console.log('本地调试')
}
Copy after login
  • Create a new vue project
vue create testvue
Copy after login

Add vueComponentDi/ to the test dependencies devDependencies under package.json under testvue index.js absolute address

"devDependencies": {
    ...
    "vuecomponentdi": "F:/vueComponent@Di/vueComponentDi",//根据自己实际项目地址填写
    ...
    }
Copy after login
  • Execute npm link

Execute npm link in testvue to soft link vuecomponentdi to node_modules

  • vuecomponentdi Install Eslint

Since testvue introduces components, Eslint detection will be performed, and an error will be reported if it is not installed (testvue can omit this step by closing Eslint)

Installation method:

 npm install eslint@6.7.2 --save-dev
 ./node_modules/.bin/eslint --init
Copy after login
  • Use vuecomponentdi in testvue

import test from "vuecomponentdi"

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
import test from "vuecomponentdi"
export default {
  name: &#39;Home&#39;,
  components: {
    HelloWorld
  },
  created(){
    test()
  }
}
</script>
Copy after login

Console Print>Local debugging

4. Develop a button component

  • button模块:进入vueComponentDi/packages/button/index.vue

type只支持传入primary属性,v-on="listeners"表示包含了父作用域中的(不含.native修饰器的)von事件监听器。它可以通过von="listeners"表示包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="listeners" 传入内部组件

<template>
    <div>
        <button class="di-button"  v-on="$listeners" :class="[type?`di-button--${type}`:&#39;&#39;]"><slot></slot></button>
    </div>
</template>
<script>
export default {
    name:"di-button",
    props:{
        type:String
    }
}
</script>
<style>
.di-button{
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #dcdfe6;
    color: #606266;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    transition: .1s;
    font-weight: 500;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    padding: 12px 20px;
    font-size: 14px;
    border-radius: 4px;
}
.di-button:focus, .di-button:hover {
    color: #409eff;
    border-color: #c6e2ff;
    background-color: #ecf5ff;
}
.di-button:active {
    color: #3a8ee6;
    border-color: #3a8ee6;
    outline: none;
}
.di-button--primary {
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
}
.di-button--primary:focus, .di-button--primary:hover {
    background: #66b1ff;
    border-color: #66b1ff;
    color: #fff;
}
.di-button--primary.is-active, .di-button--primary:active {
    background: #3a8ee6;
    border-color: #3a8ee6;
    color: #fff;
}
</style>
Copy after login
  • button模块导出:进入vueComponentDi/packages/button/index.js

如果导出一个带有install函数的对象,则在Vue2中可以直接使用Vue.use(xx)调用此函数,既执行 Vue.component(name,option)创建了一个组件

import button from "./index.vue"
button.install=(Vue)=>{
    Vue.component(button.name,button)
}
export default button
Copy after login
  • 聚合导出button:进入vueComponentDi/index.js

因为开发的组件不止一个,所以需要在入口文件统一导出

import diButton from "./packages/button"
export {
    diButton
}
Copy after login
  • 在testvue使用
<template>
  <div class="home">
    <di-button type="primary">按钮</di-button>
  </div>
</template>
<script>
// @ is an alias to /src

import Vue from &#39;vue&#39;
import {diButton} from "vuecomponentdi"
Vue.use(diButton)
export default {
  name: &#39;Home&#39;
}
</script>
Copy after login

5、开发一个toast弹窗

  • toast模块:vueComponentDi/packages/toast/index.vue

type只支持warning和success

<template>
    <div class="di-toast" :class="`di-toast--${type}`" v-if="show">
        {{message}}
    </div>
</template>
<script>
export default {
    data(){
        return {
            message:&#39;&#39;,
            show:false,
            type:&#39;&#39;
        }
    }
}
</script>
<style>
.di-toast{
    width: 60%;
    width: 200px;
    background: rgb(15, 15, 15);
    padding:3px;
    text-align: center;
    color: #fff;
    border-radius: 10px;
    position: fixed;
    left: calc(50% - 100px);
    top: 200px;
}
.di-toast--warning{
    background: #FDF6EC;
    color: #E6A28B;
}
.di-toast--success{
    background: #F0F9EB;
    color: #93C26D;
}
</style>
Copy after login
  • toast模块导出:vueComponentDi/packages/toast/index.js

因为toast弹窗需要在vue中支持this.$toast调用,所以用了Vue.extend方法,这个 API 在日常开发中很少使用,一般在开发组件的时候它才能派上用场,官方定义:使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象

import toast from &#39;./index.vue&#39;
toast.install = (Vue) => {
    const toastConstructor = Vue.extend(toast);//使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。
    let $vm = new toastConstructor();//将这个子类实例化
    let $el = $vm.$mount().$el;//$vm执行$mount()手动挂载会返回一个带有$el的对象,$el就是一个dom对象
    document.querySelector("body").appendChild($el);//将这个dom对象添加到body中
    //在Vue原型上注入$toast方法
    Vue.prototype.$toast = (option) => {
        $vm.show = true
        if (!(option instanceof Object)) {
            //如果传的不是对象直接弹出
            $vm.message = option
        } else {
            $vm.message = option.message
            $vm.type = option.type
        }
        setTimeout(() => {
            $vm.show = false
        }, 2000)
    }
}


export default toast
Copy after login
  • 聚合导出:vueComponentDi/index.js
import diButton from "./packages/button" 
import toast from "./packages/toast" 

export {
    diButton,
    toast
}
Copy after login
  • vuetest中使用toast
<template>
  <div class="home">
    <di-button type="primary" @click="toast">按钮</di-button>
  </div>
</template>
<script>
// @ is an alias to /src

import Vue from "vue";
import { diButton, toast } from "vuecomponentdi";
Vue.use(diButton);
Vue.use(toast);
export default {
  name: "Home",
  methods: {
    toast() {
      // this.toast("这是一个普通弹窗");
      // this.$toast({
      //   message: "这是一个成功弹窗",
      //   type: "success",
      // });
      this.$toast({
        message: "这是一个警告弹窗",
        type: "warning",
      });
    },
  },
};
</script>
Copy after login

6、发布到npm

  • 公有配置

组件开发完成需要发布到npm以便于别人使用;因为发布的是公有包,所以需要在vueComponentDi/package.json中配置

"publishConfig": {
    "access": "public"
  },
Copy after login

完整package.json:

{
  "name": "vuecomponentdi",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^8.2.0"
  },
  "publishConfig": {
    "access": "public"
  }
}
Copy after login
  • 发布

npm发布很简单,只需要两个命令:

npm login
npm publish
Copy after login

执行npm login需要你有npm账号,可以到 npm官网 注册

npm官网地址:https://www.npmjs.com/

发布完成之后就可以在任何一个vue2项目中安装使用了:

npm install vuecomponentdi
Copy after login

git地址: vue组件开发(https://gitee.com/geeksdidi/vue-component-di)

【相关推荐:vue.js教程

The above is the detailed content of How to create a Vue component library from scratch and publish it to npm. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks 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)

How does Vue implement component reuse and extension? How does Vue implement component reuse and extension? Jun 27, 2023 am 10:22 AM

With the continuous development of front-end technology, Vue has become one of the popular frameworks in front-end development. In Vue, components are one of the core concepts, which can break down pages into smaller, more manageable parts, thereby improving development efficiency and code reusability. This article will focus on how Vue implements component reuse and extension. 1. Vue component reuse mixins Mixins are a way to share component options in Vue. Mixins allow component options from multiple components to be combined into a single object for maximum

Vue component communication: use $destroy for component destruction communication Vue component communication: use $destroy for component destruction communication Jul 09, 2023 pm 07:52 PM

Vue component communication: Use $destroy for component destruction communication In Vue development, component communication is a very important aspect. Vue provides a variety of ways to implement component communication, such as props, emit, vuex, etc. This article will introduce another method of component communication: using $destroy for component destruction communication. In Vue, each component has a life cycle, which includes a series of life cycle hook functions. The destruction of components is also one of them. Vue provides a $de

Vue practice: date picker component development Vue practice: date picker component development Nov 24, 2023 am 09:03 AM

Vue Practical Combat: Date Picker Component Development Introduction: The date picker is a component often used in daily development. It can easily select dates and provides various configuration options. This article will introduce how to use the Vue framework to develop a simple date picker component and provide specific code examples. 1. Requirements analysis Before starting development, we need to conduct a requirements analysis to clarify the functions and characteristics of the components. According to the common date picker component functions, we need to implement the following function points: Basic functions: able to select dates, and

Vue component communication: using watch and computed for data monitoring Vue component communication: using watch and computed for data monitoring Jul 10, 2023 am 09:21 AM

Vue component communication: using watch and computed for data monitoring Vue.js is a popular JavaScript framework, and its core idea is componentization. In a Vue application, data needs to be transferred and communicated between different components. In this article, we will introduce how to use Vue's watch and computed to monitor and respond to data. watch In Vue, watch is an option, which can be used to monitor the changes of one or more properties.

Vue development notes: How to deal with complex data structures and algorithms Vue development notes: How to deal with complex data structures and algorithms Nov 22, 2023 am 08:08 AM

In Vue development, we often encounter situations where we deal with complex data structures and algorithms. These problems may involve a large number of data operations, data synchronization, performance optimization, etc. This article will introduce some considerations and techniques for dealing with complex data structures and algorithms to help developers better deal with these challenges. 1. Selection of data structures When dealing with complex data structures and algorithms, it is very important to choose appropriate data structures. Vue provides a wealth of data structures and methods, and developers can choose the appropriate data structure according to actual needs. commonly used numbers

How to use third-party libraries in Vue projects How to use third-party libraries in Vue projects Oct 15, 2023 pm 04:10 PM

Vue is a popular JavaScript framework that provides a wealth of tools and features to help us build modern web applications. Although Vue itself already provides many practical functions, sometimes we may need to use third-party libraries to extend Vue's capabilities. This article will introduce how to use third-party libraries in Vue projects and provide specific code examples. 1. Introduce third-party libraries The first step to using third-party libraries in a Vue project is to introduce them. We can introduce it in the following ways

Vue component communication: using vuex for state management communication Vue component communication: using vuex for state management communication Jul 09, 2023 am 10:16 AM

Vue component communication: Using vuex for state management communication Introduction: In Vue development, communication between components is a key issue. Vue provides a variety of ways to implement component communication, among which using vuex for state management is a common way. This article will introduce how to use vuex for component communication, and provide code examples to help readers better understand. 1. What is vuexVuex is the official state management library of Vue.js, which can realize global state management and communication between components. Vue

Vue component development: implementation method of tab page component Vue component development: implementation method of tab page component Nov 24, 2023 am 08:41 AM

Vue component development: Tab component implementation method In modern web applications, the tab page (Tab) is a widely used UI component. The Tab component can display multiple related content on a single page and switch them by clicking on the tab. In this article, we will introduce how to implement a simple tab component using Vue.js and provide detailed code examples. The structure of the Vue tab component. The tab component usually consists of two parts: tab and panel. Labels are used to identify surfaces

See all articles