2

如何统一前端项目的 Node 版本和包管理器?

 1 year ago
source link: https://www.fly63.com/article/detial/11830
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-06-29阅读: 13标签: node作者: 亖混子分享

扫一扫分享

通过文档和沟通约束,远不如用工具代码)约束。
  1. Node.js
  2. Package Manager (npm、yarn、pnpm)

成员机器 Node.js 版本不统一: 守旧派用 12.x、保守用 14.x、激进用 17.x。项目能否正常跑起来全凭天意,在没有 CICD 流水线加持本地 npm run build 的场景下线上风险可想而知。

有人习惯用 npm、有人习惯用 yarn, 代码库里面经常会存在 package-lock.json、yarn.lock 文件同时存在的情况。更痛的点还是各种奇奇怪怪问题排查起来没有头绪。

我们要做的就是将问题掐死在源头:锁定 Node.js 版本和包管理器

锁定项目 Node 版本

通过在 package.json 中指定 engines 字段,可限定项目使用的 node 版本。下面配置仅允许用户使用 14 或者 16的版本。更多的配置可以参考 package.json | npm Docs 、semver

  // package.json 
  "engines": {
    "node": "14.x || 16.x"
  },

配置之后你会发现,该字段只对 yarn 生效。那如何对 npm 也生效呢?
在项目根目录下的 .npmrc 文件中增加如下配置

// .npmrc
engine-strict = true

以上配置完成后,npm install 试试吧,错误的 Node.js 将直接退出

锁定包管理器

利用 only-allow 工具包、npm scripts 快速实现锁定。

步骤一: 在项目中 npm install -D only-allow

步骤二: 在 package.json 文件中进行配置 scripts.preinstall , 允许输入的值 only-allow npm、only-allow pnpm、only-allow yarn

// package.json
"scripts": {
    "preinstall": "npx only-allow npm",
    ...
}

以上配置完成后,可以再乱用 (yarn、npm、pnpm) 试试。

链接:https://segmentfault.com/a/1190000041918155

链接: https://www.fly63.com/article/detial/11830


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK