一、如何发包到 npm
平日常用的功能,如果多个项目里都需要用到,我们就可以通过自己发包到 npm 到,哪个项目要用到直接下载下来就能用,方便快捷。字不多打,直接上代码。
步骤为:
1. 文件夹目录图
graph TD
1.自定义一个组件 --> 2.封装一个对这些组件引入及注册的方法 --> 3.本地测试-->4.发布到npm官网上-->5.下载这个包到项目中再测试一遍
-
plugins: 是我们存放组件的文件夹
-
plugins/msg: 是我们自己写的一个消息弹窗文件夹
-
plugins/index.js: 是进行对 msg 组件的引入及注册等
2. 自定义一个组件 plugins/msg/msg.vue
<template>
<div class="msg_contaier" v-if="active">
<span>{{ text }}</span>
</div>
</template>
<script>
export default {
// 组件名要唯一
name: 'vue-msg',
data () {
return {
text: '这是默认弹窗文本',
active: false,
}
},
methods: {
showMsg(text, time=2000) {
this.active = true;
this.text = text;
setTimeout(() => {
this.active = false;
}, time);
}
},
}
</script>
<style>
.msg_contaier {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
z-index: -1;
}
span {
margin: auto;
display: inline-block;
width: 200px;
height: 40px;
background: hsl(0deg 13% 85% / 85%);
line-height: 40px;
border-radius: 4px;
color: hsl(272deg 100% 58%);
}
</style>
3. 封装 plugins/index.js 代码
// 入口文件 => 插件的入口=> 统一管理组件
/**
*动态引入文件
* require.context:表示从当前目录下找匹配 是 vue 的文件
* true:表示是否匹配子集文件夹
*/
const requireComponent = require.context('./', true, /\.vue$/);
// 插件
const install = (Vue) =>{
// 判断是否已安装当前包
if(install.installed) return;
// 如果没有安装过当前这个包,就安装
install.installed;
requireComponent.keys().forEach(fileName => {
// 第 i 个组件
const config = requireComponent(fileName);
// 组件名
const componentName = config.default.name;
// 全局安装组件
Vue.component(componentName, config.default || config);
});
// 全局自定义指令 v-focus
Vue.directive('focus', {
inserted: function(el) {
el.focus();
}
})
}
// 判断当前环境是不是 Vue 环境
if(typeof window !== 'undefined' && window.Vue) {
install(window.vue)
}
export default{
install
}
4. 本地测试
main.js中引入
import vueMsg from './plugins/index.js'
Vue.use(vueMsg)
helloWorld.vue 中使用这个组件, 发现是可以使用的
<vue-msg ref="msg" ></vue-msg>
<!-- v-focus 自定义指令 -->
<input v-focus v-model="phoneNum"/>
<button @click="callPhone">打电话</button>
5. 全局自定义指令
我们这里还全局自定义一个指令,v-focus,
// 全局自定义指令 v-focus
Vue.directive('focus', {
inserted: function(el) {
el.focus();
}
})
使用全局自定义指令, 页面刷新,发现 这个 input 自动聚焦了。
<!-- v-focus 自定义指令 -->
<input v-focus v-model="phoneNum"/>
6. 上传 npm 官网
发布插件:npm publish
二、更新 自己的npm 包
1. 升级
npm version <版本号>
2、撤销发布
npm unpublish packageName@0.0.1
或
npm unpublish packageName --force
注意:
撤销发布的包被认为是一种不好的行为,因为如果有团队使用和依赖你的包时,撤销便会造成很大的影响。
1.根据规范,只有在发包的24小时内才允许撤销发布的包
2.即使你撤销了发布的包,发包的时候也不能再和被撤销的包的名称和版本重复了(即不能名称相同,版本相同,因为这两者构成的唯一标识已经被“占用”了
三、vue 项目中升级某个插件
有时候项目中,一开始用到的框架版本比较低,后续开发的过程中,发现低版本不支持某些功能,需要对框架进行升级。
例如,我目前的项目中用到的 vxe-table,之前是 2.x 的版本,后续需要最低 3.0 的版本。
1. 手动修改 package.json 版本
1、手动修改 package.json 中的 vxe-table 框架版本,手动修改为 3.0.22 版本:再命令行中重新执行一遍 npm install 即可。