Vue 구성 요소 라이브러리를 처음부터 생성하고 npm에 게시하는 방법

青灯夜游
풀어 주다: 2022-01-13 18:38:21
앞으로
2182명이 탐색했습니다.

처음부터 Vue 구성 요소 라이브러리를 만들고 npm에 게시하는 방법은 무엇입니까? 다음 기사는 Vue 구성 요소 라이브러리를 처음부터 개발하는 방법을 단계별로 안내하고 이를 npm에 게시하는 방법을 보여줍니다. 도움이 되기를 바랍니다.

Vue 구성 요소 라이브러리를 처음부터 생성하고 npm에 게시하는 방법

1. 터미널에서 새 폴더를 열고 npm init -y

을 실행하여 다음과 같이 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"
}
로그인 후 복사

2 , 디렉토리 구조를 설정합니다

디렉토리 구조는 다음과 같습니다

-- vueComponentDi
    -- packages
        -- button
            -- index.js
            -- index.vue
        -- toast
            -- index.js
            -- index.vue
    -- index.js
    -- package.json
로그인 후 복사

3 로컬 디버깅

  • vueComponentDi/index.js
rreee
  • 새 vue 프로젝트 만들기
export default function(){
    console.log('本地调试')
}
로그인 후 복사

testvue에서 package.json 아래의 테스트 종속성은 vueComponentDi/index.js

vue create testvue
로그인 후 복사
  • Execute npm link

testvue의 npm 링크를 소프트 링크로 실행합니다. vuecomComponentdi to node_modules

  • vuecomComponentdi install Eslint

testvue에 구성 요소가 도입되었으므로 Eslint 감지가 수행되며, 설치되지 않은 경우 오류가 보고됩니다(testvue는 이 단계를 생략하기 위해 Eslint를 닫습니다)

설치 방법 :

"devDependencies": {
    ...
    "vuecomponentdi": "F:/vueComponent@Di/vueComponentDi",//根据自己实际项目地址填写
    ...
    }
로그인 후 복사
  • testvue에서 vuecomComponentdi 사용

"vuecomComponentdi"에서 테스트 가져오기

 npm install eslint@6.7.2 --save-dev
 ./node_modules/.bin/eslint --init
로그인 후 복사

콘솔 인쇄>로컬 디버깅

4 버튼 구성 요소 개발

  • 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>
로그인 후 복사
  • 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
로그인 후 복사
  • 聚合导出button:进入vueComponentDi/index.js

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

import diButton from "./packages/button"
export {
    diButton
}
로그인 후 복사
  • 在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>
로그인 후 복사

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>
로그인 후 복사
  • 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
로그인 후 복사
  • 聚合导出:vueComponentDi/index.js
import diButton from "./packages/button" 
import toast from "./packages/toast" 

export {
    diButton,
    toast
}
로그인 후 복사
  • 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>
로그인 후 복사

6、发布到npm

  • 公有配置

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

"publishConfig": {
    "access": "public"
  },
로그인 후 복사

完整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"
  }
}
로그인 후 복사
  • 发布

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

npm login
npm publish
로그인 후 복사

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

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

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

npm install vuecomponentdi
로그인 후 복사

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

【相关推荐:vue.js教程

위 내용은 Vue 구성 요소 라이브러리를 처음부터 생성하고 npm에 게시하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:juejin.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!