目录
概念
npm全称Node Package Manager,是Node.js的包管理工具,相当于前端的Maven。
安装
npm不需要单独安装,安装Node.js后,会自动安装npm。在cmd命令终端里面输入命令:npm -v可以查看当前npm的版本
配置npm镜像地址
npm官方管理的包都是从http://npmjs.com下载的,国内访问比较慢,推荐使用淘宝npm镜像:http://registry.npmmirror.com
使用如下命令配置淘宝镜像地址:
npm config set registry http://registry.npmmirror.com
通过命令:npm config list,可以查看npm配置信息
npm config list
项目初始化
- 建立一个空文件夹,然后使用命令:npm init,进行项目的初始化,会让选择输入某些信息(如package name、version、description等),可以直接按回车键以默认形式生成,如下:
PS D:\STS\yygh\npmdemo> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (npmdemo)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\STS\yygh\npmdemo\package.json:
{
"name": "npmdemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
全部选择完成后,会自动生成一个名为package.json的文件,这个是包的配置文件,相当于Maven的pom.xml。package.json如下所示:
{
"name": "npmdemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
如果想直接生成package.json文件,选项以系统自动生成,则可以使用命令:npm init y
npm install(下载依赖)
- 使用命令:npm install 依赖名称,如果不指定版本,将会安装依赖包的最新版本。如下载Vue,如下所示将会下载Vue最新版本:
npm install vue
- 模块默认安装的位置:项目目录下的node_modules文件夹中
- 依赖包会被添加到package.json文件中的dependencies节点下,类似于maven中的<dependencies>
"dependencies": {
"vue": "^3.2.40"
}
-
根据配置文件下载依赖
直接使用命令:npm install,会下载package.json配置文件里面的全部依赖
其他命令
npm update 包名 | 更新包(更新到最新版本) |
npm update -g 包名 | 全局更新 |
npm uninstall 包名 | 卸载包 |
npm uninstall -g 包名 | 全局卸载 |