npm 配置文件(.npmrc)

4 阅读1分钟

.npmrc 文件是 Node.js 的包管理工具 npm 的配置文件,它允许你设置各种配置选项来控制 npm 的行为。这个文件可以位于用户级(~/.npmrc),全局级(${prefix}/etc/npmrc,其中 {prefix} 是 npm 的安装目录,通常是 /usr/local/lib/node_modules/npm)或项目级(位于项目的根目录中,通常命名为 .npmrc)。

查看设置配置

npm config list
npm config get registry
npm config set registry https://registry.npmmirror.com/
npm config set registry http://registry.npm.taobao.org/

项目根目录配置

# .npmrc 文件 项目根目录
registry=https://registry.npmmirror.com/
@mrc-devel:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken = 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

示例 .npmrc 文件

registry=https://registry.npmjs.org/
proxy=http://proxy.example.com:8080
https-proxy=http://proxy.example.com:8080
strict-ssl=false
save=true
save-exact=true
save-dev=true
prefix=/usr/local/lib/node_modules/npm
cache=/some/path/.npm
loglevel=verbose
engine-strict=true

使用方法

要应用 .npmrc 文件中的配置,通常不需要手动执行任何操作,因为 npm 会自动读取当前目录或用户/全局配置目录下的 .npmrc 文件。如果你需要测试或调试特定的配置,可以使用命令行参数覆盖某些设置

npm install --registry https://mycustomregistry.com --save-exact some-package

注释

如果行以 ; 或 # 字符开头,则该行被视为注释。npm/ini 会解析这些注释内容。

# last modified: 01 Jan 2016
; Set a new registry for a scoped package
@myscope:registry=https://mycustomregistry.example.org

使用作用域包

企业内网下的源管理,对于发布在企业私有源的,则可以使用作用域包,二者写在一起,其中作用域包优先级更高

registry=https://registry.npm.taobao.org/
@myscope:registry=https://registry.example.com/

配置认证信息

//registry.npmjs.org/:_authToken=YOUR_AUTH_TOKEN
registry=https://your-private-registry.com/
# 用户名和密码
//your-private-registry.com/:_auth=base64_encoded_username_and_password
# Token(推荐)
//your-private-registry.com/:_authToken=your_auth_token

base64_encoded_username_and_password是你用户名和密码的base64编码

echo -n 'username:password' | base64  # 在Linux或Mac上
echo username:password | base64 -w 0  # 在Windows CMD上