npm常用指令教學-Node.js套件管理工具

12 月 29, 2018 | | 0 條留言

NPM 的安裝與使用

NPM 全名為Node Package Manager,是附屬在 Node.js 中的套件管理工具,我們在安裝 Node.js 時,就可以順便將 NPM 安裝到電腦中,並且在命令列 / 終端機模式中使用。

專案初始化

利用 npm 指令,可以協助我們建立 Node.js 專案的描述檔,或稱為初始化專案,命令如下:

//協助我們建立 Node.js 專案的描述檔
npm init

在打入 npm init 後,會被要求輸入幾個欄位

package name: 你這個 Project 要叫什麼名字
version: 你決定這個 Project 現在該是第幾版
description: Project 基本介紹
entry point: 進入點,如果要跑你的 Project 應該要執行哪個檔案
author: 作者(自己)
license: 你這個 Project 是採用什麼授權的
test command: 這個不太重要,待會會說明

基本上結束後,你可以看到這個資料夾底下,新增了一個 Package.json

如果你實際點開 package.json 來看

{
  name: my-project,
  version: 1.0.0,
  description: this is my project,
  main: app.js,
  scripts: {
    test: echo Error: no test specified && exit 1
  },
  author: alxtz,
  license: ISC
}

如果你覺得上面要一直輸入,可以使用 npm init -y快速初始化產生一個package.json

//快速開始建立專案產生一個package.json
npm init -y

安裝第三方套件

我們可以利用npm非常快速地完成套件的安裝,命令如下:

//命令格式:npm install 專案套件名稱,以下安裝 express 範例
npm install express

//使用 --save 安裝,會將專案套件加入依賴列表中,未來可以快速的恢復開發環境
npm install express --save

//使用 -g 安裝全域套件,成為共享的工具,以下安裝 firebase-tools 範例
npm install firebase-tools -g

npm 常用指令的縮寫i -S -D

//是npm install 的縮寫
npm i

//是npm install -save
npm i -S

//是npm install -save-dev
npm i -D    

npm 更新套件與解除安裝

由於 Node.js 的社群相當的活躍,套件也經常性的更新,想要將專案中的套件更新到最近的版本,或是刪除某個過時的套件,請參考以下命令:

//更新套件:npm update 可一次更新專案中的所有套件 
npm update

//可加入 -g 參數,更新全域套件
npm update -g

//刪除套件:npm uninstall 套件名稱,以下解除安裝 express 範例
npm uninstall express

//使用 -g 安裝的套件,刪除時,也必須加入 -g 參數
npm uninstall firebase-tools -g

npm list

列出目前安裝的 node module 有哪些

// 列出目前 node moulde 
npm list

輸入如上的指令,如果沒有位於任何 node project 底下的時候,是不會顯示任何模組,這是因為 npm 會去讀取 package.json,取得相依的 package 之後,再到此目錄底下的 node_modules 底下找相關模組是否已經被安裝。

// 列出全域安裝的 node module
npm list -g 

如果輸入上面的指令,就會得到目前使用 npm 已經安裝多少全域的模組,將會全部被列出來。

npm內容詳細的項目

可以參考 npm 的說明,在終端機輸入 npm ,下列指令的訊息

where <command> is one of:
    add-user, adduser, apihelp, author, bin, bugs, c, cache,
    completion, config, ddp, dedupe, deprecate, docs, edit,
    explore, faq, find, find-dupes, get, help, help-search,
    home, i, info, init, install, la, link, list, ll, ln, login,
    ls, outdated, owner, pack, prefix, prune, publish, r, rb,
    rebuild, remove, restart, rm, root, run-script, s, se,
    search, set, show, shrinkwrap, star, start, stop, submodule,
    tag, test, tst, un, uninstall, unlink, unpublish, unstar,
    up, update, version, view, whoami

npm <cmd> -h     quick help on <cmd>
npm -l           display full usage info
npm faq          commonly asked questions
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    /Users/caesar/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config</command></term></term></cmd></cmd></command>

如果想要知道每個項目要怎麼使用,可以輸入要查找的 -h,如下的範例

//加上 -h 的參數之後,就可以得到解釋。
npm remove -h
npm tag -h