vue封装公共组件库并发布到npm库

发布时间 2023-06-15 16:58:15作者: Stitchhhhh

利用的原理:
  vue框架提供的api: Vue.use( plugin),我们把封装好组件的项目打包成vue库,并提供install方法,然后发布到npm中。Vue.use( plugin )的时候会自动执行插件中的install方法。

 

一、组件库代码目录调整

1.根目录创建packages文件夹
2.在packages文件夹中新增components文件夹-用于存放所有的组件
3.在packages文件夹中新增index.js
【以后我们的所有操作都是基于packages这个文件进行的,也就是将它打包成dist】
4.把src改成examples一用于进行代码测试

 二、配置文件

1.packages/index.js文件

import MyButton from './components/MyButton.vue'

const components = [MyButton]

const install = function (Vue) {
  components.forEach(component => {
    Vue.component(component.name, component)
  })
  if (typeof window !== 'undefined' && window.Vue) {
    install(window.Vue)
  }
}
export default {
  install
}

2.新增vue.config.js配置