以下是 npm 的常用命令,适用于 macOS/Linux/Windows,作为 Node.js 的默认包管理器,功能全面且稳定。
npm install # 或 npm i,安装 package.json 中的所有依赖
npm install <package> # 安装并添加到 dependencies
npm install -D <package> # 开发依赖(devDependencies)
npm install -g <package> # 全局安装
npm uninstall <package> # 移除依赖
npm run <script> # 执行 package.json 中的脚本
npm init # 创建 package.json(加 -y 可跳过交互)
npm update # 更新所有依赖到最新兼容版
npm update <package> # 更新特定包
npm list # 或 npm ls,列出当前项目依赖
npm list -g # 列出全局依赖
~/.npm
%APPDATA%\npm-cache
(通常是 C:\Users\你的用户名\AppData\Roaming\npm-cache
)npm config get cache # 显示当前缓存路径
ls -la ~/.npm # macOS/Linux
dir "%APPDATA%\npm-cache" # Windows (PowerShell)
npm cache clean # 清理部分缓存
npm cache clean --force # 强制清空所有缓存
npm cache verify # 检查缓存完整性并修复问题
npm config get <key> # 查看某项配置,如 cache
npm config set <key> <value> # 设置配置
# 示例:
npm config set cache ~/.npm # 指定缓存路径
npm config set registry https://registry.npmjs.org/ # 设置镜像
npm config edit # 打开全局配置文件(~/.npmrc)
npm --version # 或 npm -v,显示 npm 版本
npm install --force # 忽略缓存,重新安装
npm exec <command> # 在项目环境下运行命令(7.x+)
# 示例:
npm exec node --version
npm publish # 发布到 npm 仓库
sudo chmod -R u+rw ~/.npm # macOS/Linux
npm config set registry https://registry.npmjs.orgnpm setistrynpm config set registry https://registry.npmjs.org/ # 切换官方镜像
/usr/local/lib/node_modules
%APPDATA%\npm\node_modules
npm config get prefix
npm init -y # 创建新项目
npm install @heroicons/react # 安装依赖
npm config get cache # 检查缓存位置
npm run dev # 运行开发脚本
npm cache clean --force # 清理缓存
add
替代 install <package>
。