← Systems Foundations

TOOLING FOUNDATION · 79

npm / package.json / node_modules / Lockfile:Dependency 到底怎麼進專案

npm 不是 Node runtime;package.json 也不是「安裝清單而已」。現代 JavaScript 專案需要一個可重現的 dependency graph、scripts contract 與 package manager workflow。

Learning outcomes

1. package.json 是 project metadata + dependency intent

{
  "scripts": {
    "check":
      "node scripts/check.js",
    "build":
      "node scripts/build.js"
  },
  "dependencies": {
    "express": "^5.0.0"
  }
}

2. npm install 解 dependency graph

package.json
  ↓ npm install
registry metadata/packages
  ↓
node_modules
  +
lockfile

node_modules 是安裝結果,不應當作唯一 source of truth。

3. Lockfile 鎖住解析結果

Semver range 可能允許多個版本;lockfile 記錄實際解析出的版本與 integrity,讓不同機器/CI 更接近同一 dependency tree。

package.json:
  express ^5.x

lockfile:
  exact resolved version
  transitive dependencies
  integrity metadata

4. dependencies vs devDependencies

Runtime 需要的 package 與只在 build/test/lint 階段需要的工具,應依專案 deployment model 正確分類。不要只為了「看起來乾淨」任意搬動。

5. npm scripts 是團隊 command contract

npm run check
npm run build
npm test

把複雜命令包成 scripts,讓本機與 CI 使用同一入口。

Project checkpoint:Tooling Contract

替 Course Workspace 定義 check、test、build scripts,確保新 clone 不依賴個人 global package。

fresh clone
  ↓
install dependencies
  ↓
npm run check
  ↓
npm test
  ↓
npm run build

Debug evidence:本機能跑、CI 說 command not found

檢查 package 是否其實只裝在 global、lockfile 是否同步、runner Node/npm version、install step 是否成功。不要把 global environment 當專案 dependency。

Knowledge check

  1. Node 與 npm 的角色差在哪?
  2. Lockfile 為何對 CI 重要?
  3. node_modules 是否適合作為唯一 source of truth?
  4. 把三個長 command 重構成 package scripts。