npm 常用命令

使用淘宝镜像

为了能下载依赖包速度快点,推荐使用淘宝镜像,使用下面命令修改镜像地址:

1
npm config set registry https://registry.npm.taobao.org

初始化模块

下面命令初始化一个模块,按提示配置 package.json 中的字段。

1
npm init 

-y 表示使用默认值配置 package.json 文件中的字段,

安装

使用下面命令安装模块:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
npm install (with no args, in package dir)
npm install [<@scope>/]<name>
npm install [<@scope>/]<name>@<tag>
npm install [<@scope>/]<name>@<version>
npm install [<@scope>/]<name>@<version range>
npm install <alias>@npm:<name>
npm install <git-host>:<git-user>/<repo-name>
npm install <git repo url>
npm install <tarball file>
npm install <tarball url>
npm install <folder>

aliases: npm i, npm add
common options: [-P|--save-prod|-D|--save-dev|]

可选参数:

  • -P, –save-prod: 表示生产环境依赖包
  • -D, –save-dev: 表示开发环境依赖包

例子:

1
2
3
4
5
#直接写包名 从镜像地址下载 lodash
npm i lodash
#从git url 下载lodash
npm i git+https://github.com/lodash/lodash.git

更新

1
2
3
npm update [-g] [<pkg>...]

aliases: up, upgrade

-g 参数表示更新全局安装包

如果不指定包名称,将更新所有的安装包到满足需要的最新版本。

卸载

1
2
3
npm uninstall [<@scope>/]<pkg>[@<version>]... [-S|--save|-D|--save-dev|-O|--save-optional|--no-save]

aliases: remove, rm, r, un, unlink

例子:

1
npm uninstall lodash --no-save

查看已装包列表

通过下面命令查看已安装列表,带 -g 表示查看全局目录的

1
npm ls [-g]

清理缓存

使用 -f 参数可以强制清理缓存

1
npm cache clear [-f]

npm 配置

1
2
3
4
5
6
7
8
9
npm config set <key> <value> [-g|--global]
npm config get <key>
npm config delete <key>
npm config list [-l] [--json]
npm config edit
npm get <key>
npm set <key> <value> [-g|--global]

aliases: c

例子:

1
npm config list  #获取所有配置信息

帮助

1
npm help <term> [<terms..>]

当指定了具体的命令时,会打开对应命令的文档,如 npm help install 会打开 install 命令的帮助文档。