跳轉到

3.1 package.json 與 npm 基本操作#

npm 是什麼?#

npm(Node Package Manager) 有兩個身份:

  1. 命令列工具:安裝、管理套件
  2. 套件庫網站:世界上最大的開源套件庫(npmjs.com)

初始化專案:npm init#

每個 Node 專案都從 package.json 開始——它是專案的身分證,記錄名稱、版本、依賴與腳本:

npm init -y    # -y = 全部用預設值,直接生成

生成的 package.json:

{
  "name": "my-project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  }
}

安裝套件:npm install#

npm install express        # 安裝套件並加入 dependencies(可簡寫 npm i)
npm install -D eslint      # 安裝開發用工具(-D = devDependencies)
npm install                # 依 package.json 安裝全部依賴(clone 專案後必跑)
npm uninstall express      # 移除套件

安裝後,專案裡會多出:

  • node_modules/:套件的實體檔案(不要 commit 進 Git)
  • package.json:記錄裝了哪些套件(要 commit)
  • package-lock.json:鎖定確切版本(要 commit,見 3.3 節)

鐵律:node_modules/ 一定要加進 .gitignore。有了 package.json + lock 檔,任何人 npm install 就能重建一模一樣的環境。

更新與查看#

npm outdated        # 查看哪些套件有新版
npm update          # 更新到允許範圍內的最新版
npm ls              # 查看已安裝的依賴樹

package.json 的核心欄位#

{
  "name": "my-project",
  "type": "module",
  "scripts": { ... },
  "dependencies": { "express": "^4.19.0" },
  "devDependencies": { "eslint": "^9.0.0" }
}
  • "type": "module":啟用 ESM 模組系統(見 1.3 節)
  • scripts:自訂快捷指令(見 3.3 節)
  • dependencies / devDependencies:依賴分類(見 3.2 節)