npm(Node Package Manager) 是 Node.js 的包管理工具,用于:
-
安装、更新、卸载 JavaScript 的第三方库(如 jQuery、Cypress、Playwright 等);
-
管理项目依赖关系;
-
运行项目脚本任务(如测试、构建、启动);
-
发布/下载 JS 模块包(来自 npmjs.com)。
注:运行
npm install
之前,必须先切换到你的项目目录,否则会出错或安装在错误位置。
cd D:\web\crm-admin # 第一步:切换到项目根目录
npm install # 第二步:安装当前项目所需依赖
npm 的几个核心概念
概念 | 作用说明 |
---|---|
package.json |
项目的配置文件,列出了依赖包、脚本命令等 |
node_modules/ |
所有安装的依赖会放到这个目录 |
package-lock.json |
锁定依赖的精确版本,保证团队每次 npm install 都一致 |
devDependencies |
仅用于开发时的包(如测试、构建工具) |
dependencies |
项目运行时需要的包(如 jQuery、axios 等) |
命令速查表
命令 | 作用 |
---|---|
npm init |
创建 package.json (你也可以用 npm init -y 快速生成) |
npm install <包名> |
安装一个依赖(默认存到 dependencies ) |
npm install --save-dev <包名> |
安装到 devDependencies ,常用于测试类工具 |
npm uninstall <包名> |
卸载一个依赖 |
npm run <脚本名> |
执行 package.json 里的脚本命令 |
npm update |
更新所有包 |
npm outdated |
查看哪些包过时了 |
一个典型前端项目的 package.json
{
“name”: “crm-admin”,
“version”: “1.0.0”,
“scripts”: {
“test”: “cypress run”,
“test:e2e”: “playwright test”
},
“dependencies”: {
“jquery”: “^3.7.1”
},
“devDependencies”: {
“cypress”: “^13.6.2”,
“playwright”: “^1.45.0”
}
}
你可以通过命令执行对应脚本:
npm run test # 跑 Cypress 测试
npm run test:e2e # 跑 Playwright 测试
npm 与中国开发者
npm 官方服务器在国外,有时安装较慢。你可以使用淘宝源加速:
npm config set registry https://registry.npmmirror.com
npm install xxx