toFrankie / blog

种一棵树,最好的时间是十年前。其次,是现在。
20 stars 1 forks source link

npm 安装时锁定版本 #305

Open toFrankie opened 1 year ago

toFrankie commented 1 year ago

配图源自 Freepik

我们知道,使用 npm 或 yarn 安装包时,它会以 ^x.y.z 形式添加到 package.json 里面。

{
  "devDependencies": {
    "typescript": "^5.0.2"
  }
}

可通过 save-prefixsave-exact 进行修改:

npm 配置文件的作用范围可分为 globaluserproject,但通常我们只要关注 userproject 就行,对应的配置文件在 ~/.npmrc/path/to/project/.npmrc

# 用户级别
$ npm config set save-prefix '~'

# 项目级别
$ npm config set save-prefix '~' --location project
# 用户级别
$ npm config set save-exact true

# 项目级别
$ npm config set save-exact true --location project

其中 npm config 修改配置是 user 级别的(通常意义上的全局配置)。当然你也可以直接修改对应配置文件(其中 .npmrc 为 ini 格式)。

由于 yarn v1 会读取 .npmrc 作为补充,通常我们只要使用 npm config 去设置即可。

Related Link