如何将自己写的vue插件发布在npm上面

89 阅读1分钟

第一,先建一个目录机构eg package,里面有index.js,你的业务功能 eg:

image.png 当你的业务功能写完以后,在业务目录新建一个index.js

import Module from './Measure.vue'

// 给组件定义install方法
Module.install = Vue => {
    Vue.component(Module.name, Module)
}
export default Module

其次编写package目录下的index.js

import tree from './tree'

const components = [tree]

const install = Vue => {
    // 判断组件是否安装,如果已经安装了就不在安装。
    if (install.installed) return
    install.installed = true
    // 遍历的方式注册所有的组件
    components.map(component => Vue.use(component))
}

// 检查vue是否安装,满足才执行
if (typeof window !== 'undefined' && window.Vue) {
    install(window.Vue)
}

export default {
    // 所有的组件必须有一个install的方法,才能通过Vue.use()进行按需注册
    install,
    ...components,
}

在package.json中添加打包代码(name说的是打包后的文件夹名称,dest说的是打包后的文件名称)

image.png

允许完打包命令后,就生成了一个目录 radiationFile

之后cd进入这个目录,在终端只npm init 生成一个package.json文件

image.png 之后npm切换到npm的镜像源,执行npm login输入你的账号密码和邮箱

登录成功以后执行npm publish就将插件发布到了npm上面