【规范】统一项目中包管理器的使用
2023-02-18 16:41:28 时间
Dear,大家好,我是“前端小鑫同学”,?长期从事前端开发,安卓开发,热衷技术,在编程路上越走越远~
【规范】统一项目中包管理器的使用
背景介绍:
我们这里暂不说各种包管理器的优缺点,在实际开发中遇到的一个问题就是,你本地经常使用cnpm来安装,但Jenkins自动构建用的npm,偶尔就会出现本地开发很正常但是Jenkins构建失败报警了,为了避免类似问题的出现,也应该要将能统一的都统一规范。
实现原理:
- 通过preinstall来在执行install前执行指定脚本;
- 在preinstall脚本中获取当前执行进程中包管理器的唯一属性;
- 确定执行的和预设的是否一致,拦截或者放行。 一、UserAgent方案
- 通过npm_config_user_agent来获取当前执行的是包管理器的名称和版本
- 通过对比名称来限制非允许的包管理器执行安装 1. npm_config_user_agent: 同开源项目方案:which-pm-runs
npm/6.14.5 node/v14.17.1 win32 x64
yarn/1.22.10 npm/? node/v14.17.1 win32 x64
2. 完整脚本:
const allowPM = 'yarn'
const userAgent = process.env.npm_config_user_agent || ''
if (userAgent !== '') {
const pmName = userAgent.substring(0, userAgent.indexOf('/'))
if (pmName !== allowPM) {
console.warn(
`\u001b[33m This repository requires using ${allowPM} as the package manager for scripts to work properly.\u001b[39m\n`
)
process.exit(1)
}
}
{
"scripts": {
"preinstall": "node ./preinstall.js"
}
}
二、ExecPath方案
- 通过npm_execpath来获取当前执行的包管理器绝对路径
- 通过正则匹配路径中的名称来限制非允许的包管理器执行安装1. npm_execpath: 同开源项目方案:vue-next,scripts\preinstall.js
C:\Users\OSpoon\AppData\Roaming\nvm\v14.17.1\node_modules\npm\bin\npm-cli.js
C:\Users\OSpoon\AppData\Roaming\npm\node_modules\yarn\bin\yarn.js
2. 完整脚本:
const allowPM = 'yarn'
const execpath = process.env.npm_execpath || ''
if (!new RegExp(`${allowPM}`).test(execpath)) {
console.warn(
`\u001b[33m This repository requires using ${allowPM} as the package manager for scripts to work properly.\u001b[39m\n`
)
process.exit(1)
}
{
"scripts": {
"preinstall": "node ./preinstall.js"
}
}
三、only-allow方案
only-allow为pnpm包管理器组织开源限制方案,only-allow内部使用which-pm-runs来获取当前执行的包管理器后再进行判断拦截,仅需在安装依赖后调整scripts中的内容即可,在vite项目中有使用。
{
"scripts": {
"preinstall": "npx only-allow yarn"
}
}
相关文章
- @Validated – 接口参数校验注解
- thingsboard设备状态更新可能导致的不一致性问腿
- windows升级docker-compose
- 理解YACC中符号的优先级和结合性
- compose--修饰符Modifier
- compose--CompositionLocal、列表LazyColumn&LazyRow、约束布局ConstraintLayout
- SAP ABAP CDS view Association 引入的缘由
- OnD1操练纪要-微信朋友圈权限领域建模操练
- 贪吃蛇复现-CoCube
- 共享主机和 WordPress 主机之间的区别
- 如何在 WordPress 中嵌入 iFrame
- 第十四届蓝桥杯集训——JavaC组第八篇——进制转换
- 第十四届蓝桥杯集训——JavaC组第九篇——位运算符
- 第十四届蓝桥杯集训——JavaC组第九篇——三元运算符
- 【数据挖掘】薪酬分段对应工作经验/学历画柱状图【招聘网站的职位招聘数据预处理】
- Grafana 的介绍和安装
- SpringSecurity用户绑定到线程
- SpringSecurity权限过滤
- 汇编学习(6), 外部函数,调用约定
- 汇编学习(7), Bit 操作