一、文件位置

全局配置文件:/etc/npmrc
用户配置文件:~/.npmrc
项目配置文件:$项目根目录/.npmrc

优先级:项目配置>用户配置>全局配置。npm会先按照优先级从低到高依次读取配置文件,如果多个配置文件都配置了同一个key,后读取的会覆盖之前的。例如,在用户配置文件和项目配置文件中都配置了registry地址,npm会先读取用户配置,再读取项目配置,项目配置里配置的registry地址会覆盖用户配置里的registry地址。

通过npm config 修改的是用户配置文件(~/.npmrc)

二、命令行

设置文件key-value

npm config set key value
如设置仓库信息
npm config set registry [https://repo.huaweicloud.com/repository/npm/](https://repo.huaweicloud.com/repository/npm/)


三、.npmrc文件配置

配置仓库

registry=https://repo.huaweicloud.com/repository/npm/


根据scope设置仓库

@aa:registry=https://repo.huaweicloud.com/repository/npm/


配置npm的全局安装目录,使用npm -g安装东西时会安装到这里

prefix=/usr/local/npm


配置node-sass等模块仓库

  1. sass_binary_site=https://repo.huaweicloud.com/node-sass
  2. phantomjs_cdnurl=https://repo.huaweicloud.com/phantomjs
  3. chromedriver_cdnurl=https://repo.huaweicloud.com/chromedriver
  4. operadriver_cdnurl=https://repo.huaweicloud.com/operadriver



自定义缓存目录

cache=~/.cache/npm_cache


配置仓库认证信息,用于私有仓库读取或上传npm包

  1. always-auth=true
  2. _auth="用户名:密码"base64编码


在多私库且用户名密码不同的情况下,可以对单个私库配置_auth

  1. # :前为仓库地址去掉http:/https:
  2. //repo.huaweicloud.com/repository/npm/:_auth=xxxxxx


除了使用用户名密码,还可以通过配置_authToken配置认证信息

_authToken=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx


配置当通过https向注册中心发出请求时,不进行SSL密钥验证(一般不推荐,不安全)

strict-ssl=false


四、如何配置发布组件

npm配置组件发布的方式有两种,一种是通过配置packege.json实现,另一种则是通过配置文件.npmrc实现。

package.json配置方式

  1. # @aa是组件的scope。scope在模块名name中使用时,以@开头,后边跟一个/
  2. {
  3. "name": "@aa/xxx", // 发布npm包的名字
  4. "version": "1.0.0", // 你的npm包版本
  5. "description": "xxxx", // 包的描述
  6. "main": "dist/btn.js", // 指定组件的主入口文件
  7. "publishConfig": {
  8. "registry": "要发布的私有仓库地址,然后在.npmrc配置用户名密码"
  9. }
  10. ......
  11. }


.npmrc配置方式

  1. # package.json不做任何仓库的配置:
  2. {
  3. "name": "@aa/xxx", // 发布npm包的名字
  4. "version": "1.0.0", // 你的npm包版本
  5. "description": "xxxx", // 包的描述
  6. "main": "dist/btn.js", // 指定组件的主入口文件
  7. ......
  8. }
  9. # .npmrc配置仓库地址和用户名密码:
  10. @aa:registry=私仓地址


配置好仓库信息后,执行发布命令即可将打包好的组件发布到仓库中

npm publish


五、使用带有scope的模块

  1. #在package.json的dependencies标签中加上即可使用。
  2. "dependencies": {
  3. "@aa/mypackage": "^1.3.0"
  4. }