npm常见命令

22 阅读2分钟
# 初始化项目
npm init          # 交互式创建 package.json
npm init -y       # 快速创建默认 package.json

# 安装依赖
npm install           # 简写:npm i,安装 package.json 中的所有依赖
npm install [包名]    # 安装指定包并添加到 dependencies
npm install -D [包名] # 安装到 devDependencies(简写:--save-dev)
npm install -g [包名] # 全局安装包(需管理员权限)

# 卸载依赖
npm uninstall [包名]       # 移除包并更新 package.json
npm uninstall -g [包名]    # 全局卸载包

# 更新依赖
npm update [包名]       # 更新到兼容的最新版本(遵循 SemVer)
npm install [包名]@latest # 强制更新到最新版本
npm outdated            # 查看可更新的依赖

# 运行自定义脚本
npm run [脚本名]    # 运行 package.json 中 scripts 字段定义的命令
npm start           # 简写:npm run start,默认执行 "node server.js"
npm test            # 简写:npm run test"
npm run dev         # 示例:运行开发服务器

# 生命周期钩子
npm install         # 触发 preinstall → install → postinstall
npm publish         # 触发 prepublish → prepare → prepublishOnly → publish → postpublish

# 查看包信息
pm view [包名]         # 查看包的详细信息(版本、作者等)
npm view [包名] versions # 查看所有可用版本
npm info [包名]         # 同 npm view

# 版本管理
npm version patch       # 增加补丁版本(如 1.0.0 → 1.0.1)
npm version minor       # 增加次版本(如 1.0.0 → 1.1.0)
npm version major       # 增加主版本(如 1.0.0 → 2.0.0)

# 全局包安装
npm list -g --depth=0   # 查看全局安装的包
npm outdated -g         # 查看全局可更新的包

# 配置管理
npm config list         # 查看所有配置
npm config get registry # 查看 npm 源
npm config set registry https://registry.npmjs.org # 设置官方源
npm config set registry https://registry.npmmirror.com # 设置淘宝源

# 发布包
npm adduser           # 创建npm账号
npm login             # 登录 npm 账户
npm publish           # 发布包到 npm
npm unpublish [包名] --force # 强制删除已发布的包(72小时内)

# 安全审计
npm audit             # 检查依赖中的安全漏洞
npm audit fix         # 自动修复安全漏洞

# 调试命令
npm install --verbose # 详细输出安装过程
npm cache clean --force # 清除缓存
npm doctor            # 检查环境配置

# 临时执行命令
npx [命令]            # 临时安装并执行命令,无需全局安装
npx create-react-app my-app # 示例:创建 React 项目

# 其它命令
npx depcheck         # 检查未使用的依赖