本文旨在帮助我记录Npm和Yarn工具的一些常用命令。由于昨天学习了以下当前比较火的Vue框架,从而顺藤摸瓜有接触到了Npm和Yarn。但是在使用的过程中发现百度能搜出来的东西真是有限。第一页搜索结果基本上就是一篇原创加九篇拷贝,在零星加两条广告。由于Npm和Yarn在工作中不常用,还是记录下来,不至于下次用到再花费大把时间放在搜索上。
#1. 查询当前安装的模块
由于Npm和Yarn都可以指定全局安装和当前项目安装。刚接触的时候,我都是选择全局安装的,现在回过头来想想,还是按项目安装比较好。原因就不多说了。以下命令是查看全局安装了什么,如何删除。
使用Npm或Yarn查询
npm list npm list -g npm list -g --depth=0 #yarn yarn list yarn list -g --depth=0
转载自https://stackoverflow.com/questions/10972176/find-the-version-of-an-installed-npm-package。如果要查看是否安装了某个包,比如Vue:
npm list vue npm list -g vue #yarn yarn list vue yarn global list vue
使用Npm或Yarn删除
npm uninstallnpm uninstall --save npm uninstall --save-dev npm -g uninstall --save #yarn yarn remove yarn global remove
转载https://stackoverflow.com/questions/13066532/how-to-uninstall-npm-modules-in-node-js
删除所有安装的全局模块
这里再附上如何删除所有安装的全局模块,转自https://stackoverflow.com/questions/9283472/command-to-remove-all-npm-modules-globally/9283646
npm ls -gp --depth=0 | awk -F/ '/node_modules/ && !/\/npm$/ {print $NF}' | xargs npm -g rm
暂时没有找到如何用yarn删除全部安装的包。
#2. 查询仓库中模块最新版本
如果我们准备安装某个模块,或者已经安装了某个模块,想要了解自己的模块是不是最新版本。可以通过以下命令查看:
npm view electron version npm view electron versions #yarn yarn info electron
#3. 跟新安装模块的最新版本
如果我们发现有更新的版本,并且如果不考虑兼容性问题的话,我们可以使用以下命令更新安装模块:
npm update electron npm update electron@latest --save #yarn yarn upgrade yarn upgrade electron@^8.0.0 yarn upgrade electron --latest
备注:不知道以下内容是不是仍然有效。
“^8.0.0” —–向上的尖括号可以管理二级,三级版本
“~8.0.0” —–波浪线可以管理三级版本。
#4. Yarn网络连接错误
无论是Yarn还是NPM都需要联网下载大量第三方库,很多情况会出现网络连接不上的问题。例如:
There appears to be trouble with your network connection. Retrying
网上的解决方案也很多,以下是我尝试成功的一个方案(来自互联网):
yarn config set registry https://registry.npm.taobao.org yarn config delete proxy npm config rm proxy npm config rm https-proxy npm install -g cnpm --registry=https://registry.npm.taobao.org npm config set registry https://registry.npm.taobao.org
#5. Yarn全局安装require找不到模块问题
这个主要原因是Yarn全局安装的包路径不在NodeJS查找模块的路径列表中。主要的问题比如使用如下指令全局安装mongodb模块:
yarn global add mongodb
安装成功以后在node文件中引用mongodb库显示如下:
const { MongoClient } = require('mongodb'); Uncaught Error: Cannot find module 'mongodb'
我们可以在Node终端中使用module.paths
命令查看NodeJS查找模块的路径:
使用yarn global dir
查看yarn的全局安装目录,并使用module.paths.push
把yarn的全局安装目录添加进去即可。
module.paths.push("/Users/james/.config/yarn/global/node_modules") const { MongoClient } = require('mongodb');

扫码联系船长