NPM包管理器

image.png

NPM安裝和定義

NPM(全稱 Node Package Manager,即「node包管理器」)是Node.js默認的、以JavaScript編寫的 軟件包管理系統

以上是維基百科給NPM的定義。理解軟件包管理系統。
軟件包管理系統是在計算機中自動安裝、配製、卸載和升級軟件包的工具組合,在各類系統軟件和應用軟件的安裝管理中均有普遍應用。
好比:PHP中composer、JAVA中maven、LIUNX系統中的yumhtml

NPM軟件包管理系統由3部分組成:前端

  • 網站 

能夠經過https://www.npmjs.com網站,搜索包、管理本身的包和我的信息。vue

  • 註冊表(registry)

一個巨大的數據庫,保存着每一個包(package)的信息。node

  • 命令行工具 (CLI)

經過命令行和終端運行,開發者經過CLI與NPM打交道。


在安裝Node.js時會默認安裝NPM包管理器,NPM徹底由Javascript寫成,和模塊沒啥區別,因此咱們能夠npm install -g npm 更新安裝本身。react

隨着前端工程化、模塊化的快速發展,前端開發已經離不開npm包管理器了。在咱們使用前端各大框架Vue、React、Angluar時,咱們只須要npm install [package name]就能夠安裝使用咱們須要的模塊包,很是便捷高效。git

經過下圖咱們就能看出npm之火爆。總包量100多萬,周下載量114億。來自各大洲的開源軟件開發者都在使用npm借鑑學習或者分享。同時也是Node.js得到成功重要緣由之一。
image.png
github

NPM命令以及使用

image.png

以上圖片羅列出NPM全部的命令,撿幾個經常使用的命令學習;
web

npm install 安裝模塊

安裝形式:redis

npm install (with no args, in package dir)
npm install [<@scope>/]<pkg>
npm install [<@scope>/]<pkg>@<tag>
npm install [<@scope>/]<pkg>@<version>
npm install [<@scope>/]<pkg>@<version range>
npm install <folder>
npm install <tarball file>
npm install <tarball url>
npm install <git:// url>
npm install <github username>/<github project>

alias: i,add
common options: [-S|--save|-D|--save-dev|-O|--save-optional] [-E|--save-exact][--no-save][-B|--save-bundle][--dry-run]

其中:
-S與--save 安裝到dependenices生產環境中,對應package.json中的dependencies數據庫

//npm i -S ecpress || npm install --save express
"dependencies": {
    "express": "^4.17.1",
}

-D與--save-dev 安裝到devDependenices開發環境中,對應package.json中的devDependencies

//npm i -D ecpress || npm install --save-dev express
"devDependencies": {
    "express": "^4.17.1"
 }

-O與--save-optional 安裝加入到可選階段依賴對應package.json中的optionalDependencies

// npm i -O vue || npm install --save-optional
"optionalDependenices":{
    "vue": "^2.5.2"
}

 -E與--save-exact 精準安裝指定模塊版本對應package.json中的dependenicies不會是兼容的模式展現^

// npm i -E vue || npm install --save-exact 注意沒有^
"dependenices":{
    "vue": "2.5.2"
}

--no-save 防止保存到依賴項

-B與--save-bundle 保存的依賴項也將添加到您的bundleDependencies列表中。

"dependenices":{
    "vue":"^2.5.2"
},
"bundleDependencies":["vue"]

--dry-run 只在命令行能夠看到有安裝的操做,實際沒有安裝任何內容到node_modulespackage.json

本地安裝

npm i vue

全局安裝

npm i -g vue || npm install --global vue

即便本地已經下載,強制從遠程下載安裝

npm i -f vue || npm install --force vue

npm uninstall 卸載模塊

npm uninstall [<@scope>/]<pkg>[@<version>]... [-S|--save-prod][-D|--save-dev][-O|--save-optional] [--no-save]

aliases: un, unlink, remove, rm, r
npm uninstall -g vue //卸載全局包
npm uninstall vue // 卸載本地包

npm search 搜索模塊

npm search [-l|--long] [--json] [--parseable] [--no-description] [search terms ...]

aliases: s, se, find

npm update 更新模塊

npm update [-g] [<pkg>...]

aliases: up, upgrade, udpate

npm outdated 檢查模塊是否過期

npm outdated [[<@scope>/]<pkg> ...]

npm ls 查看安裝模塊

npm ls [[<@scope>/]<pkg> ...]

aliases: list, la, ll

npm init 初始化 生成package.json文件

npm init [--force|-f|--yes|-y|--scope]
npm init <@scope> (same as `npx <@scope>/create`)
npm init [<@scope>/]<name> (same as `npx [<@scope>/]create-<name>`)

默認init 跳過提示步驟

npm init -y || npm init -yes

安裝react應用到my-react-app目錄下

npm init react-app ./my-react-app

init 轉成npx對應操做

npm init foo -> npx create-foo
npm init @usr/foo -> npx @usr/create-foo
npm init @usr -> npx @usr/create

npm help <term> || npm <command> -h查看命令幫助

npm help install
npm help init
npm install -h || npm install --help

npm root 查看包安裝路徑

npm root
# 查看全局安裝路徑
npm root -g

npm config 管理npm配置項

npm config set <key> <value> [-g|--global]
npm config get <key>
npm config delete <key>
npm config list [-l] [--json]
npm config edit
npm get <key>
npm set <key> <value> [-g|--global]

aliases: c

基本配置

npm config list
; cli configs
metrics-registry = "https://registry.npmjs.org/"
scope = ""
user-agent = "npm/6.4.1 node/v10.15.3 darwin x64"

; userconfig /Users/ducen/.npmrc
//registry.npm.taobao.org/:always-auth = false
init.author.email = "123@.qq.com"
registry = "https://registry.npmjs.org/"

; node bin location = /usr/local/bin/node
; cwd = /Users/ducen/Learn/npm
; HOME = /Users/ducen
; "npm config ls -l" to show all defaults.

npm cache 管理模塊緩存

npm cache add <tarball file>
npm cache add <folder>
npm cache add <tarball url>
npm cache add <name>@<version>
npm cache clean [<path>]

aliases: npm cache clear, npm cache rm

npm cache verify

默認緩存位置mac~/.npm window %AppData%/npm-cache
最經常使用的是清除本地緩存

npm cache clean

npm version 查看模塊版本

npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease [--preid=<prerelease-id>] | from-git]
npm version
{ npm: '6.4.1',
  ares: '1.15.0',
  cldr: '33.1',
  http_parser: '2.8.0',
  icu: '62.1',
  modules: '64',
  napi: '3',
  nghttp2: '1.34.0',
  node: '10.15.3',
  openssl: '1.1.0j',
  tz: '2018e',
  unicode: '11.0',
  uv: '1.23.2',
  v8: '6.8.275.32-node.51',
  zlib: '1.2.11' 
}

npm view 查看模塊註冊信息

npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]
aliases: info, show, v
npm view vue
vue@2.6.10 | MIT | deps: none | versions: 250
Reactive, component-oriented view layer for modern web interfaces.
https://github.com/vuejs/vue#readme

keywords: vue

dist
.tarball: https://registry.npmjs.org/vue/-/vue-2.6.10.tgz
.shasum: a72b1a42a4d82a721ea438d1b6bf55e66195c637
.integrity: sha512-ImThpeNU9HbdZL3utgMCq0oiMzAkt1mcgy3/E6zWC/G6AaQoeuFdsl9nDhTDU3X1R6FK7nsIUuRACVcjI+A2GQ==
.unpackedSize: 3.0 MB

maintainers:
- yyx990803 <yyx990803@gmail.com>

dist-tags:
beta: 2.6.0-beta.3  csp: 1.0.28-csp     latest: 2.6.10

published 3 months ago by yyx990803 <yyx990803@gmail.com>

npm view <pkg> dependencies查看模塊的依賴關係

npm view express dependecies
{ 
    accepts: '~1.3.7',
  'array-flatten': '1.1.1',
  'body-parser': '1.19.0',
  'content-disposition': '0.5.3',
  'content-type': '~1.0.4',
  cookie: '0.4.0',
  'cookie-signature': '1.0.6',
  debug: '2.6.9',
  depd: '~1.1.2',
  encodeurl: '~1.0.2',
  'escape-html': '~1.0.3',
  etag: '~1.8.1',
  finalhandler: '~1.1.2',
  fresh: '0.5.2',
  'merge-descriptors': '1.0.1',
  methods: '~1.1.2',
  'on-finished': '~2.3.0',
  parseurl: '~1.3.3',
  'path-to-regexp': '0.1.7',
  'proxy-addr': '~2.0.5',
  qs: '6.7.0',
  'range-parser': '~1.2.1',
  'safe-buffer': '5.1.2',
  send: '0.17.1',
  'serve-static': '1.14.1',
  setprototypeof: '1.1.1',
  statuses: '~1.5.0',
  'type-is': '~1.6.18',
  'utils-merge': '1.0.1',
  vary: '~1.1.2' 
  }

npm view <pkg> repository.url 查看源文件地址

npm view qs repository.url
git+https://github.com/ljharb/qs.git

npm view <pkg> contributors 查看模塊的貢獻值

npm view express contributors
[ 'Aaron Heckmann <aaron.heckmann+github@gmail.com>',
  'Ciaran Jessup <ciaranj@gmail.com>',
  'Douglas Christopher Wilson <doug@somethingdoug.com>',
  'Guillermo Rauch <rauchg@gmail.com>',
  'Jonathan Ong <me@jongleberry.com>',
  'Roman Shtylman <shtylman+expressjs@gmail.com>',
  'Young Jae Sim <hanul@hanul.me>' ]

npm adduser 用戶登陸

npm adduser [--registry=url] [--scope=@orgname] [--always-auth] [--auth-type=legacy]

aliases: login, add-user
npm adduser
Username: alan-du
Password:
Email: (this IS public) 316358726@qq.com
Logged in as alan-du on https://registry.npmjs.org/.

用戶登陸後,能夠向npm發送包。

npm publish 發佈模塊

npm publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>] [--otp otpcode] [--dry-run]

Publishes '.' if no argument supplied
Sets tag 'latest' if no --tag specified

簡單發一個包

#1
mkdir alan-npm-test
#2
cd alan-npm-test
#3
npm init -y
#4
touch index.js
#5
echo "function(){console.log('這是發佈的測試包')}()">index.js
#6
npm adduser
Username: alan-du
Password:
Email: (this IS public) 316358726@qq.com
Logged in as alan-du on https://registry.npmjs.org/.
#7
npm publish
npm notice
npm notice 📦  alan-npm-test@1.0.0
npm notice === Tarball Contents ===
npm notice 227B package.json
npm notice 58B  index.js
npm notice === Tarball Details ===
npm notice name:          alan-npm-test
npm notice version:       1.0.0
npm notice package size:  353 B
npm notice unpacked size: 285 B
npm notice shasum:        4c84a14ed93f4e1e6d2a603da3e70868f71035e4
npm notice integrity:     sha512-IgzS/4dB/vFVD[...]lzv4Fq4Pw2rnA==
npm notice total files:   2
npm notice
+ alan-npm-test@1.0.0

npm dist-tag 添加刪除查看tag

npm dist-tag add <pkg>@<version> [<tag>]
npm dist-tag rm <pkg> <tag>
npm dist-tag ls [<pkg>]

aliases: dist-tags
#1
npm dist-tag ls
alan-npm-test@1.0.2-0: 1.0.2-0
latest: 1.0.3-1
npm-test@1.0.5: 1.0.5
#2
npm dist-tag rm alan-npm-test alan-npm-test@1.0.2-0
-alan-npm-test@1.0.2-0: alan-npm-test@1.0.2-0

npm deprecate 棄用包

npm deprecate <pkg>[@<version>] <message>
npm deprecate alan-npm-test@1.0.3-1 "this package has been deprecated"

image.png
<message>不能爲漢字等特殊字符

npm unpublish撤銷發佈的包

刪除某個版本

npm unpublish alan-npm-test@1.0.5

刪除整個npm市場的包

npm unpublish alan-npm-test --force

24小時內你能夠刪除本身發佈的庫,而且沒有被下載,以後你就不再能刪除了。

package.json 介紹

{
  "name": "express",
  "description": "Fast, unopinionated, minimalist web framework",
  "version": "4.17.1",
  "author": "TJ Holowaychuk <tj@vision-media.ca>",
  "contributors": [
    "Aaron Heckmann <aaron.heckmann+github@gmail.com>",
    "Ciaran Jessup <ciaranj@gmail.com>",
    "Douglas Christopher Wilson <doug@somethingdoug.com>",
    "Guillermo Rauch <rauchg@gmail.com>",
    "Jonathan Ong <me@jongleberry.com>",
    "Roman Shtylman <shtylman+expressjs@gmail.com>",
    "Young Jae Sim <hanul@hanul.me>"
  ],
  "license": "MIT",
  "repository": "expressjs/express",
  "homepage": "http://expressjs.com/",
  "keywords": [
    "express",
    "framework",
    "sinatra",
    "web",
    "rest",
    "restful",
    "router",
    "app",
    "api"
  ],
  "dependencies": {
    "accepts": "~1.3.7",
    "array-flatten": "1.1.1",
         ...
  },
  "devDependencies": {
    "after": "0.8.2",
    "connect-redis": "3.4.1",
       ...
  },
  "engines": {
    "node": ">= 0.10.0"
  },
  "files": [
    "LICENSE",
    "History.md",
    "Readme.md",
    "index.js",
    "lib/"
  ],
  "scripts": {
    "lint": "eslint .",
    "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/",
    "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/",
    "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/",
    "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/"
  }
}

name

在package.json中最重要的就是name和version字段。他們都是必須的,若是沒有就沒法install。name和version一塊兒組成的標識在假設中是惟一的。改變包應該同時改變version。

version

version必須能被node-semver解析,它被包在npm的依賴中。(要本身用能夠執行npm install semver
可用的「數字」或者「範圍」見下文語義化版本控制範圍SemVer.

description

放簡介,字符串,方便在npm search中搜索

keywords

關鍵字,數組、字符串,方便在npm search中搜索

bugs

項目提交問題的url和(或)郵件地址

"bugs": {
    "url": "https://github.com/vuejs/vue/issues"
 }

license

指定一個許可證,讓人知道使用的權利和限制的。
最簡單的方法是,假如你用一個像BSD或者MIT這樣通用的許可證,就只須要指定一個許可證的名字,像這樣:

"license": "MIT",

若是你又更復雜的許可條件,或者想要提供給更多地細節,能夠這樣:

"licenses" : [
  { 
   "type" : "MyLicense", 
   "url" : "http://github.com/owner/project/path/to/license"
  }
]

repository

指定你的代碼存放的地方。這個對但願貢獻的人有幫助。若是git倉庫在github上,那麼npm docs命令能找到你。
這樣作:

"repository": {
    "type": "git",
    "url": "git+https://github.com/vuejs/vue.git"
  },

URL應該是公開的(即使是隻讀的)能直接被未通過修改的版本控制程序處理的url。不該該是一個html的項目頁面。由於它是給計算機看的。

scripts

「scripts」是一個由腳本命令組成的hash對象,他們在包不一樣的生命週期中被執行。key是生命週期事件,value是要運行的命令。

"scripts": {
    "dev": "rollup -w -c scripts/config.js --environment TARGET:web-full-dev",
        ...
 },

更多詳細請看 npm-scripts(7)

config

"config": {
    "commitizen": {
      "path": "./node_modules/cz-conventional-changelog"
    }
 }

config對象可用於設置在升級過程當中持久存在的程序包腳本中使用的配置參數。例如,若是包具備如下內容:

dependencies

生產依賴包,請不要將測試或過渡性的依賴放在dependencies中。

"dependencies": {
    "accepts": "~1.3.7",
    "array-flatten": "1.1.1",
         ...
 },

devDependencies

開發依賴包,若是有人要使用你的模塊,那麼他們可能不須要你開發使用的外部測試或者文檔框架。
在這種狀況下,最好將這些附屬的項目列在devDependencies中。

"devDependencies": {
    "after": "0.8.2",
    "connect-redis": "3.4.1",
       ...
 },

語義化版本控制規範(SemVer)Semantic Versioning

SemVer規則

版本格式:主版本號.次版本號.修訂號,版本號遞增規則以下:

  1. 主版本號:當你作了不兼容的 API 修改;
  2. 次版本號:當你作了向下兼容的功能性新增;
  3. 修訂號:當你作了向下兼容的問題修正;

先行版本號及版本編譯元數據能夠加到「主版本號.次版本號.修訂號」的後面,做爲延伸。
當主版本號升級後,次版本號和修訂號須要重置爲0,次版本號進行升級後,修訂版本須要重置爲0。

SemVer 兩個概念

  • 固定版本:是指例如 0.4.一、1.2.七、1.2.4-beta.0 這樣表示包的特定版本的字符串;
  • 範圍版本:是對知足特定規則的版本的一種表示,例如 1.2.3-2.3.四、1.x、^0.二、>1.4;

先行版本(Pre-release Version

先行版本號能夠做爲發佈正式版以前的版本,格式是在修訂版本號後面加上一個鏈接號(-),再加上一連串以點(.)分割的標識符,標識符能夠由英文、數字和鏈接號([0-9A-Za-z-])組成。

1.0.0-alpha
1.0.0-alpha.1
1.0.0-0.3.7
1.0.0-x.7.z.92

常見的先行版本號名稱:

  • alpha:是內部測試版,通常不向外部發布,會有不少Bug.通常只有測試人員使用;
  • beta:也是測試版,這個階段的版本會一直加入新的功能。在Alpha版以後推出;
  • rc:Release Candidate) 系統平臺上就是發行候選版本。RC版不會再加入新的功能了,主要着重於除錯;

依賴規則

npm依賴的規則,有^~><=>=<=-||xX* 等符號;

**^**:表示同一主版本號,不小於當前指定版本號的版本好號。

dependencies:{
    vue:"^2.6.2" 
}
// npm install 安裝最新依賴,會下載2.6.三、2.7.1 不會下載2.6.一、3.0.0

~ :表示同一主版本號和次版本號中,不小於指定版本號的版本號。

dependencies:{
    vue:"~2.6.2" 
}
// npm install 安裝最新依賴,會下載2.6.三、2.6.6 不會下載2.6.1 2.7.0

<、=、>=、<=、-:用來指定一個版本號範圍。

dependencies:{
    vue:">2.6.2", 
},
"engines": {
  node: ">= 0.10.0"
},
//`1.1.1 - 1.2.0`
//注意使用 `-` 的時候,必須兩邊都有空格。

||:表示或

dependencies:{
    vue:"<2.6.2 || >2.5.1", 
},

xX*:表示通配符

dependencies:{
    qs:"*",
  vue:"2.x"
},
//`*` 對應全部版本號
//`2.x` 對應全部主版本號爲 2 的版本號

npm經常使用命令詳解
一分鐘教你發佈一個npm包
NPM模塊的TAG管理
package.json英文文檔
package.json中文文檔
Semver 中文網
Semver 語義化版本規範

相關文章
相關標籤/搜索