npm --save 到底是什麼 --save-dev 不一樣嗎
--save vs --save-dev
TL;DR==--save = dependencies(生產環境也需要),如 React、axios。--save-dev (-D) = devDependencies(只在開發時需要),如 TypeScript、ESLint。npm 5+ 起 --save 是預設行為==,可省略。
主要參考[NodeJs] npm --save 到底是什麼? --save-dev 不一樣嗎?(itsems-frontend)](https://medium.com/itsems-frontend/nodejs-npm-dependencies-devdependencies-8934f641c8ef)
兩種 dependency 的差別
# 進 dependencies(預設,production 也裝)
npm install react
# 等同於 npm install --save react
# 進 devDependencies(只開發時用)
npm install -D typescript
# 或 npm install --save-dev typescript
// package.json
{
"dependencies": {
"react": "^18.0.0" // ⭐ production 也安裝
},
"devDependencies": {
"typescript": "^5.0.0" // ⭐ 只 dev 安裝
}
}
何時用哪個
| 套件型別 | 用 --save | 用 --save-dev |
|---|---|---|
| UI 框架(React, Vue) | ✅ | |
| HTTP 客戶端(axios) | ✅ | |
| Runtime utility(lodash, dayjs) | ✅ | |
| Backend SDK(Express, Prisma) | ✅ | |
| State 管理(Redux, Zustand) | ✅ | |
| TypeScript | ✅ | |
型別定義(@types/*) | ✅ | |
| 測試工具(Jest, Vitest) | ✅ | |
| Lint / Format(ESLint, Prettier) | ✅ | |
| 打包工具(Webpack, Vite) | ✅ | |
| Git hooks(Husky) | ✅ |
判斷準則
問自己:「這個套件在 production server 跑時還需要嗎?」
| 答案 | 用法 |
|---|---|
| 會 | dependencies |
| 只在開發 / build 時需要 | devDependencies |
# 範例:寫 React 元件用了 dayjs 處理時間 → production 渲染時要用
npm install dayjs
# 範例:用 Vitest 寫單元測試 → production 不會跑測試
npm install -D vitest
production 安裝(skip devDependencies)
# 只裝 dependencies(deploy / Docker 內常用)
npm ci --omit=dev
# 或 npm install
npm install --production # 舊寫法
NODE_ENV=production npm install # 也行
Docker production image 必須 omit dev,否則 image 大十倍。
第三類:peerDependencies
有時你會看到第三種:
{
"peerDependencies": {
"react": "^18.0.0"
}
}
適合:你寫的 library(別人 install 你的套件)。peerDependencies 告訴使用者「你必須裝這個 package 才能用我」。
為什麼不用 dependencies:避免 react 被裝兩次(主專案一份 + library 一份),會有 hook 錯誤等問題。
第四類:optionalDependencies
選擇性安裝,失敗也不會讓 npm install 報錯:
{
"optionalDependencies": {
"fsevents": "^2.0.0" // macOS 才有,其他平台 skip
}
}
平台特定 套件用這個。
2026 年現實
npm 5(2017)起 --save 是預設,但寫 --save 不會錯,只是冗餘:
npm install react # 等同
npm install --save react # 等同
npm install -S react # 等同
# devDependencies 必須明確
npm install --save-dev typescript
npm install -D typescript
今天還在文件看到 --save 是文件沒更新,不影響行為。