使用npm发布vue组件
创建/配置NPM包项目
1.0> 创建 Vue Cli
项目
2.0> 创建 npm
组件入口文件(src/index.js
),文件内容通常如下:
import Test from './components/0-test/Test.vue'
const cusComponents = [
Test,
];
const install = function(Vue, opts = {}) {
if (install.installed) return
// a>. 将所有组件都注册为全局组件
cusComponents.map(component =>{
Vue.component(component.name, component);
});
// b>. 在原型链上挂接工具方法
Vue.prototype.$toast = toast
Vue.prototype.$dialog = dialog
}
// 支持自动安装
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue) // 通过use方式全部引入
}
export default {
install, // 用户安装组件库后,可调用use方法一次性自动引入所有所有组件
Test // 支持用户单独引入某些组件
}
3.0> 配置 package.json
文件,并设置入口文件路径
注:配置项 main 用于设置组件入口文件路径;若设置为"src/index.js",则用户引入的组件为未编译的源码;若设置为"dis/index.js",则用户引入的是已编译代码;
{
"name": "vue-custom-components",
"version": "0.1.1",
"private": false,
"main": "src/index.js", // 重点
"description": "Vue工具库",
...
}
发布NPM包
1.0> 使用 npm 官方仓库,只有切换为 npm 官方仓库才能完成登录、发包等操作
npm config set registry https://registry.npmjs.org/
2.0> 登录 npm 账号
npm login
3.0> 发布 npm 包
npm publish
4.0> 切换回淘宝镜像
npm config set registry https://registry.npm.taobao.org