npm使用总结
2020-05-12
3 min read
概述
npm全称node package manager,即node的包管理工具。npm是JavaScript世界的包管理工具,并且是Node.js平台的默认包管理工具。通过npm可以安装、共享、分发代码,管理项目依赖关系。
package.json
package.json是npm包的入口,涵盖了这个包的基本信息。通过使用npm init可以自动创建该文件。
一个创建的 package.json 文件如下:
{
"name": "foo",
"version": "1.0.0",
"description": "test ",
"main": "index.js",
"scripts": {
"test": "jest"
},
"dependencies": {
"ramda": "^0.25.0",
"react": "^16.0.0"
},
"repository": {
"type": "git",
"url": "test.git"
},
"keywords": [
"some",
"keywords"
],
"author": "Bob",
"license": "MIT"
}
- 其中
main代表的是此包的入口文件,当别的包进行let foo = require('foo')的时候,引用的其实就是这个main字段说指向的index.js文件。 scripts代表这个 npm 包中运行的命令dependencies代表这个 npm 包所依赖的别的包,当npm install foo的时候,会将这个包所依赖的包也一同安装。
~与^代表什么?
在 package.json 中的 dependencies JSON对象中会有这样的代码:
"dependencies": {
"ramda": "^0.25.0",
"react": "~16.0.0"
}
~ 代表在项目中更新包(npm update)的时候,可以更新到最新的一个patch版本即从0.25.0 => 0.25.x,但不包括 0.26.x。
^ 代表在项目中更新包(npm update)的时候,可以更新到最新的一个minor版本(即第二位的版本号),即从16.0.0 => 16.x.x,但不包括17.x.x。
常用命令
安装模块
局部安装(在当前所在路径下安装)
npm install <module name>
全局安装
npm intall -g <module name>
卸载模块
npm uninstall <module name>
查看安装信息
查看局部安装的模块
npm list
查看全局安装的模块
npm list -g
更改源
全局更改
设置淘宝源
npm set registry https://registry.npm.taobao.org
设置官方源
npm set registry http://registry.npmjs.org
局部更改,在项目中使用
创建 .yarnrc 或者 .npmrc 文件,在文件中写入如下内容:``` registry "http://npm.xxx.com/"
注:rc (run control)
#### 获取当前使用的源
``` npm config get registry (npm get registry)```