平常开发反复使用npm install的时候太多了,而大多数时候它又很是的慢。因此动手研究一下如何优化。node
先找到两个影响速度的瓶颈:git
网络链接问题。github
NPM install的机制问题。npm
别名法小程序
alias cnpm="npm --registry=https://registry.npm.taobao.org
配置文件法缓存
npm config set registry https://registry.npm.taobao.org
直接用第三方的npm服务器
npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install
提示: 可使用一些小工具进行切换,例如nrv网络
$npm install -g nrm $nrm ls * npm ----- https://registry.npmjs.org/ cnpm ---- http://r.cnpmjs.org/ taobao -- https://registry.npm.taobao.org/ nj ------ https://registry.nodejitsu.com/ rednpm -- http://registry.mirror.cqupt.edu.cn skimdb -- https://skimdb.npmjs.com/registry $nrm use taobao
npm-proxy-cache工具
local-npm: https://github.com/nolanlawso...优化
npm-lazy
1.没法npm publish。
由于publish频次不高,须要的时候切换回npm的官方registry就能够了。
2.自动选择问题
有的一套脚本可能会在国内和国外不一样的服务器上运行,例如CI服务器在国外实际开发和部署在国内。这个时候就须要自动的选择合适的registry。
我本身写了个小程序来支持这种场景,https://github.com/guolin/ufnr
自己依赖不多下载快,并可以根据不一样的环境切换合适的registry。 以为好给个星 :)
$ npm install -g ufnr $ ufnr current registry is https://registry.npm.taobao.org
没有离线模式,必须访问网络
顺序执行,效率差
解决离线和缓存的方法有:
上面提到的local-npm,至关于本地搭建一个registry镜像
替换npm install,例如,npm-cache 等
--cache-min: 这个参数能够强制使用本地缓存,例如,
npm install --cache-min 999 xx // 强制优先使用本地999分钟内的缓存
这种方法的缺点有两点;
1. 若是缓存中有对应的包依然须要发送Etag验证是否须要更新。 2. 若是缓存中有版本不对应的包则直接报错。(而不是下载正确的包)
yarn是facebook推出的解决方案,貌似也获得了npm的官方支持。解决了npm的主要问题,但网络链接问题依然须要切换registry来实现。