npm:Node Package Manager node包管理工具
npm不需要单独安装,只要搭建好了node环境就自动安装了npm
什么是包?
包可以简单的理解为包含一个或者多个模块的文件夹
什么是模块?
在 node开发中,依照CommonJs规范,一个文件就是一个模块
npm的作用
发布、安装和管理包
常用命令
npm config list :查看npm相关的配置 其中prefix为全局安装的地址
全局安装一般用于安装全局使用的工具,存储在全局的node_modules中(npm config list中的prefix)
npm install -g 包名(默认安装最新版本的包)
npm install -g 包名@版本号 (安装指定版本的包)
npm uninstall -g 包名 :卸载全局安装的包
npm update -g 包名:更新包(默认更新到最新的版本)
注意点:如果使用npm update -g 包名 出现问题,那么直接使用npm install -g 包名将包更新为最新版本
本地安装一般用于安装当前项目使用的包,存储在当前项目的node_modules中
本地安装前要先初始化一个package.json,初始化命令:npm init -y
什么是package.json?
package.json是包描述文件,定义了当前项目所需的各种模块,以及项目的配置信息(比如名称、版本号等元数据)
{
"name": "08-npm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
注意点:package.json文件中, 不能加入任何注释
npm install 包名
npm install 包名@版本号
npm uninstall 包名
npm update 包名
执行了npm install jquery后,可以看出package.json中添加了一个dependencies
{
"name": "08-npm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jquery": "^3.4.1"
}
}
执行了npm install swiper --save后,dependencies中多了一个swiper
{
"name": "08-npm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jquery": "^3.4.1",
"swiper": "^5.0.4"
}
}
执行了npm install iscroll --save-dev后,package.json中多了一项devDependencies
{
"name": "08-npm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jquery": "^3.4.1",
"swiper": "^5.0.4"
},
"devDependencies": {
"iscroll": "^5.2.0"
}
}
我们来讨论一下dependencies和devDependencies的区别
- dependencies:生产环境包的依赖,一个关联数组,由包的名称和版本号组成
- devDependencies:开发环境包的依赖,一个关联数组,由包的名称和版本号组成
1.将项目拷贝给其它人, 或者发布的时候, 我们不会将node_modules也给别人, 因为太大
2.因为有的包可能只在开发阶段需要, 但是在上线阶段不需要, 所以需要分开指定
拿到package.json后需要执行的命令:
npm i 所有的包都会被安装
npm i --development 所有的包都会被安装
npm i --production 只会安装dependencies中的包
npm的各种命令
查看本地/当前文件下是否安装某个包
npm ls 包名
如果安装了就显现版本号
如果没有安装则显示 --UNMET DEPENDENCY 包名