Skip to content

npm 常用命令

说明

收集开发中常用的 npm 命令,涵盖镜像配置、项目初始化、包管理等场景。

镜像相关

查看镜像源地址

bash
npm config get registry

# yarn
yarn config get registry

设置镜像源地址

以设置淘宝镜像源为例:

bash
npm config set registry https://registry.npmmirror.com

# yarn
yarn config set registry https://registry.npmmirror.com

使用镜像地址下载包

bash
# 下载所有包
npm install --registry=https://registry.npmmirror.com

# 下载指定包
npm install <package-name> --registry=https://registry.npmmirror.com

项目初始化

npm init 命令用于初始化一个新的 npm 项目。从 npm@6 开始,支持使用社区编写的生成器来初始化项目。

基本用法

bash
# 生成 package.json 文件
npm init [--force|-f|--yes|-y|--scope]

# 使用指定的生成器生成文件
npm init <@scope> (same as `npx <@scope>/create`)
npm init [<@scope>/]<name> (same as `npx [<@scope>/]create-<name>`)

示例

使用 create-react-app 初始化项目:

bash
npm init react-app my-app
# OR
npm create react-app my-app

注意

npxnpm v7 中被重写,单独的 npx 包已被弃用。当执行 npx 时会被转换为 npm exec 命令。

在使用指定的生成器时 init 命令会转换为相应的 npxnpm exec 操作:

npm v6 (npx)

  • npm init foo -> npx create-foo
  • npm init @usr/foo -> npx @usr/create-foo

npm v7+ (npm exec)

  • npm init foo -> npm exec create-foo
  • npm init @usr/foo -> npm exec @usr/create-foo

别名

除了使用 npm init 外,还可以使用 npm createnpm innit 进行初始化。

管理 package.json

获取字段信息

bash
# 获取 package.json 所有字段
npm pkg get

# 获取 package.json 中指定字段的信息
npm pkg get <field>

# 示例
npm pkg get name
npm pkg get name version
npm pkg get scripts.test

设置字段

bash
npm pkg set <field> <value>

# 示例
npm pkg set name='maomao' engines.node='>=18'

删除字段

bash
npm pkg delete <key>

# 示例
npm pkg delete scripts.build

依赖管理

查看已安装的依赖包

bash
# 当前项目
npm list --depth 0

# 全局
npm list -g --depth 0

# yarn
yarn global list --depth=0

查看依赖包的安装路径

bash
# 当前项目
npm root

# 全局
npm root -g

# yarn
yarn global dir

清除缓存

bash
npm cache clean -f

# yarn
yarn cache clean

文档与社区

打开文档

bash
# 在浏览器中打开当前项目的文档
npm docs

# 在浏览器中打开指定 npm 包的文档
npm docs [package-name]

打开 GitHub Repo

bash
# 在浏览器中打开当前项目的 GitHub repo
npm repo

# 在浏览器中打开指定 npm 包的 GitHub repo
npm repo [package-name]

打开 GitHub Issues

bash
# 在浏览器中打开当前项目的 GitHub issues
npm bugs

# 在浏览器中打开指定 npm 包的 GitHub issues
npm bugs [package-name]

脚本命令

执行顺序

  • 并行执行:使用 &
  • 继发执行:使用 &&
bash
# 并行执行:同时启动 script1 和 script2
npm run script1.js & npm run script2.js

# 继发执行:先执行 script1,成功后再执行 script2
npm run script1.js && npm run script2.js

获取当前脚本名称

在脚本中可以通过环境变量获取当前正在运行的脚本名称:

javascript
process.env.npm_lifecycle_event

如有转载或 CV 的请标注本站原文地址