zl程序教程

您现在的位置是:首页 >  Java

当前栏目

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

2023-02-18 16:41:28 时间

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

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

背景介绍:

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

实现原理:

  1. 通过preinstall来在执行install前执行指定脚本;
  2. 在preinstall脚本中获取当前执行进程中包管理器的唯一属性;
  3. 确定执行的和预设的是否一致,拦截或者放行。 一、UserAgent方案
  4. 通过npm_config_user_agent来获取当前执行的是包管理器的名称和版本
  5. 通过对比名称来限制非允许的包管理器执行安装 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方案

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

三、only-allow方案

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

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