【规范】统一项目中包管理器的使用

「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」。

Dear,大家好,我是“前端小鑫同学”,😇长期从事前端开发,安卓开发,热衷技术,在编程路上越走越远~


【规范】统一项目中包管理器的使用

背景介绍:

我们这里暂不说各种包管理器的优缺点,在实际开发中遇到的一个问题就是,你本地经常使用cnpm来安装,但Jenkins自动构建用的npm,偶尔就会出现本地开发很正常但是Jenkins构建失败报警了,为了避免类似问题的出现,也应该要将能统一的都统一规范。

实现原理:

  1. 通过preinstall来在执行install前执行指定脚本;
  2. 在preinstall脚本中获取当前执行进程中包管理器的唯一属性;
  3. 确定执行的和预设的是否一致,拦截或者放行。

一、UserAgent方案

  1. 通过npm_config_user_agent来获取当前执行的是包管理器的名称和版本
  2. 通过对比名称来限制非允许的包管理器执行安装

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"
}
}

image.png

二、ExecPath方案

  1. 通过npm_execpath来获取当前执行的包管理器绝对路径
  2. 通过正则匹配路径中的名称来限制非允许的包管理器执行安装

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"
}
}

image.png

三、only-allow方案

only-allow为pnpm包管理器组织开源限制方案,only-allow内部使用which-pm-runs来获取当前执行的包管理器后再进行判断拦截,仅需在安装依赖后调整scripts中的内容即可,在vite项目中有使用。

{
"scripts": {
"preinstall": "npx only-allow yarn"
}
}

image.png


欢迎关注我的公众号“前端小鑫同学”,原创技术文章第一时间推送。

posted @   前端小鑫同学  阅读(10)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示