这是我参与8月更文挑战的第2天
1.注意
本文主要是模拟常见的utils打包到npm私有仓储,适用于公司好几个项目,有很多重复的组件,utils,想减少代码复用,较少维护成本,建立私有仓储,不公开
2. 打包成npm 包的流程(utils代码)
2.1 vue页面代码以及utils
vue页面
<template>
<div id="app">
call me : {{ userPrivate(phone) }}
<br>你的捐款是{{ money }}, 总共有 {{ userPrivate(money)}} 位数
</div>
</template>
<script>
import { userPrivate, getNumBit } from './utils/index'
export default {
name: 'App',
data() {
return {
phone: 18819168888,
money: 12345.88,
userPrivate,
getNumBit,
}
}
}
</script>
utils
/**
* 用户手机信息加密显示
* @param { Number, String } phone 用户手机/帐号
*/
module.exports = {
// 给电话号码加密
userPrivate(phone) {
const phoneStr = String(phone)
if (!phone || phoneStr.length < 11) return phone
const privateIndex = phoneStr.indexOf('86') > -1 ? 5 : 3
return `${phoneStr.substring(0, privateIndex)}****${
phoneStr.substring(privateIndex + 4, phoneStr.length)}`
},
// 获取数字的整数位长度
getNumBit(num) {
let intNum = num.toFixed(0);
return intNum.length;
}
}
2.2 将utils打包到npm
1. 安裝使用 Verdaccio (一定全局安装哦,只有在运行时候才能使用)
npm install -g verdaccio
verdaccio
2. 新建包bingxixi-private-common-utils
->将utils的index.js放到bingxixi-private-common-utils文件底下(直接做入口文件)->初始化
mkdir bingxixi-private-common-utils
这里的包名,我是由 项目名+功能
cd bingxixi-private-common-utils
3 提交
1.切换到bingxixi-private-common-utils文件地下
cd bingxixi-private-common-utils
2.添加.npmrc 可以通过指令npm config edit进行编辑,你的包就是发布到127.0.0.1:4873的私有仓储
3.初始化
npm init
这里如果文件名没问题的话,直接enter就好
4.添加自己得帐号到私服
npm adduser
把自己输入的帐号记住哦~
- 发布
npm publish
6.查看
- 如何更新版本发布
刚刚我们没有加上包的说明,所以在bingxixi-private-common-utils文件里面新建一个md文件,叫做README.md,
md里面的内容.可以在npm上搜一个包,参考模仿
npm version patch
npm publish
注意:npm version patch是在你原有的版本号,假设v1.0.0,他会在这个基础上加1,如果你的版本不是加1,你可以不用npm version patch,直接手动改package.json,然后再npm publish
8.成果
3.vue 页面如何使用
1.添加.npmrc
可以通过指令npm config edit进行编辑,或者直接用vscode打开.npmrc文件,这样的话,优先从私有仓储下包
2.下载包
npm i bingxixi-private-common-utils -S
3.页面处理
main.js里面引入,并且全局注册
import { userPrivate, getNumBit } from 'bingxixi-private-common-utils'
Vue.prototype.$userPrivate = userPrivate
Vue.prototype.$getNumBit = getNumBit
vue组件页面
<template>
<div id="app">
call me : {{ $userPrivate(phone) }}
<br>你的捐款是{{ money }}, 总共有 {{ $userPrivate(money)}} 位数
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
phone: 18819168888,
money: 12345.88,
}
}
}
</script>