npm 命令入门指南(前端小白版)_登陆 npm 命令
npm 命令入门指南(前端小白版)
1. npm 是什么?
- Node Package Manager:Node.js 的包管理工具,用于安装、分享 JavaScript 工具/库。
- 核心功能:
- ✅ 安装第三方库(如 React、Vue)
- ✅ 管理项目依赖
- ✅ 发布自己的插件
2. 最常用命令
npm init
package.json
(项目说明书)npm init -y
(快速创建)npm install
npm install lodash
npm run
npm run dev
npm update
npm update react
npm publish
npm publish
3. npm 仓库类型
registry.npmmirror.com
4. 如何更换仓库?
(1) 临时切换镜像(单次生效)
npm install lodash --registry=https://registry.npmmirror.com
(2) 永久切换镜像
npm config set registry https://registry.npmmirror.com
(3) 恢复官方仓库
npm config set registry https://registry.npmjs.org
(4) 验证当前仓库
npm config get registry
5. 提交插件到 npm 仓库
步骤 1:注册 npm 账号
👉 访问 npmjs.com/signup
步骤 2:登录 npm
npm login # 输入用户名/密码/邮箱
步骤 3:初始化插件项目
mkdir my-plugin && cd my-pluginnpm init -y # 生成 package.json
步骤 4:编写代码
// index.jsmodule.exports = () => console.log(\"Hello Plugin!\");
步骤 5:发布!
npm publish # 自动上传到 npm 仓库
注意:
- 包名在
package.json
的\"name\"
中定义(需全网唯一)- 更新版本:
npm version patch
+npm publish
常见问题
- 安装卡住? → 换淘宝镜像
npm config set registry https://registry.npmmirror.com
- 发布失败? → 检查包名是否重复或未登录
- 插件汉化? → 在
package.json
添加中文描述字段
小白学习路径
- 用
npm install
装几个库(如axios
) - 尝试创建
package.json
- 发布一个测试插件(名字加后缀如
my-plugin-test123
)
官方文档:npm Docs
中文资源:npm 淘宝镜像
📌 npm 全局安装位置、缓存位置及查看方法(完整指南)
🔍 1. 全局安装位置
📂 默认路径
%AppData%\\npm\\node_modules
/usr/local/lib/node_modules
或 /usr/lib/node_modules
🔎 如何查看当前全局安装路径?
npm root -g
输出示例(Windows):
C:\\Users\\你的用户名\\AppData\\Roaming\\npm\\node_modules
🔎 如何查看全局安装的包?
npm list -g --depth=0
输出示例:
/usr/local/lib├── npm@10.2.3├── nrm@1.2.5└── yarn@1.22.19
🔍 2. 全局可执行文件位置
全局安装的包的可执行文件(如 create-react-app
)会被链接到以下目录:
%AppData%\\npm
/usr/local/bin
🔎 如何查看全局可执行文件路径?
which npm # macOS/Linuxwhere npm # Windows
🔍 3. npm 缓存位置
npm 下载的包会缓存到以下目录:
%AppData%\\npm-cache
~/.npm
🔎 如何查看当前缓存路径?
npm config get cache
输出示例:
C:\\Users\\你的用户名\\AppData\\Roaming\\npm-cache
🔎 如何查看缓存内容?
npm cache ls
输出示例(部分):
~/.npm/_cacache/content-v2/sha512/xx/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
🔍 4. 实用命令汇总
npm root -g
npm list -g --depth=0
which
(Linux/macOS) / where
(Windows)npm config get cache
npm cache ls
npm cache clean --force
npm uninstall -g
🚨 常见问题排查
-
权限问题(macOS/Linux)
如果全局安装失败,可能是权限不足,尝试:sudo chown -R $(whoami) /usr/local/lib/node_modules
或使用
npx
临时运行(无需全局安装)。 -
缓存占用过大
定期清理缓存:npm cache clean --force
-
路径冲突
如果npm root -g
和which npm
路径不一致,可能是环境变量NODE_PATH
配置错误,检查:echo $NODE_PATH
🎯 总结
- 全局安装路径:
npm root -g
- 可执行文件路径:
which
或where
- 缓存路径:
npm config get cache
- 缓存清理:
npm cache clean --force
掌握这些命令后,你可以轻松管理 npm 的全局包和缓存,避免磁盘空间浪费和路径冲突问题!