發布自己的npm包
發布自己的 npm 套件
TL;DR流程:註冊 npm 帳號 → npm login → npm publish。有 scope name(@username/pkg)要加 --access public,否則預設 private(要付費)。版本管理走 semver(1.2.3 = major.minor.patch)。
基本流程
# 1. 註冊 npm 帳號(npmjs.com)
# 2. 登入(會問 username / password / email / OTP)
npm login
# 3. 確認登入身份
npm whoami
# 4. package.json 設定好(name / version / main / files / etc)
# 5. 發布
npm publish
npm publish 會把 package.json + 你 include 的檔案上傳,自動讀 README.md 當作介紹頁。
scope 套件(@username/pkg-name)
# 預設是 private,要付費
npm publish
# 公開發布
npm publish --access public # ⭐ 必加
scope 套件 像是 @bobo100/cra-template-bobonext.js,必須加 --access public 才會公開發布。
更新版本
# 用 npm version 自動更新版號 + 打 git tag
npm version patch # 1.0.0 → 1.0.1(bugfix)
npm version minor # 1.0.1 → 1.1.0(新功能,向後相容)
npm version major # 1.1.0 → 2.0.0(breaking change)
# 然後發布
npm publish --access public
規則:版本必須 大於現在線上版本,不能往下改。發布錯了 24 hr 內可以 unpublish,過期就只能廢棄(deprecate)。
package.json 必要欄位
{
"name": "@bobo100/my-package",
"version": "1.0.0",
"description": "簡短描述",
"main": "dist/index.js", // 入口
"module": "dist/index.esm.js", // ESM 入口(modern)
"types": "dist/index.d.ts", // TS 型別
"files": [ // ⭐ 哪些檔要 publish
"dist/",
"README.md",
"LICENSE"
],
"keywords": ["react", "..."],
"author": "Bobo",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Bobo100/my-package"
}
}
files 欄位很重要,沒設會把 node_modules / 測試檔等垃圾全 ship 出去。
進階做法(2026)
1. 用 changesets 管版本
適合 monorepo / 多 package 同時發版:
npm install --save-dev @changesets/cli
npx changeset init
npx changeset # 互動式選 patch/minor/major
npx changeset version # 套用版號
npx changeset publish # 發布
2. CI 自動發版
# .github/workflows/publish.yml
on:
push:
branches: [main]
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: 'https://registry.npmjs.org'
- run: npm ci
- run: npm run build
- run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
NPM_TOKEN 從 npmjs.com → Account → Access Tokens 產生。
常見地雷
1. 套件名搶占熱門名稱可能被搶。發布前先 npm view <name> 確認。 個人套件建議用 scope 開頭(@username/pkg),不會撞名。
2. 沒設 .npmignore / filesnpm 預設打包整個資料夾(除了 .gitignore + node_modules)。 用 files 欄位明確列出要 ship 的目錄。
3. README 沒更新npm 頁面 會顯示 README,publish 前確認 README 內容對應到當前版本。
4. 版本號 prereleasenpm version 1.0.0-beta.1 npm publish --tag beta # ⭐ 別人 install 時要 npm install pkg@beta預設 install 不會抓到 prerelease 版本,要加
--tag。
替代發布平台
| 平台 | 特色 |
|---|---|
| npm registry | 預設 |
| GitHub Packages | 跟 GitHub 整合 |
| JSR | 2024 推出,Deno 出的下一代 registry |
| 私有 registry | Verdaccio 自架 |
2026 年觀察 JSR,Deno team 出的,主打更好的 TypeScript 支援、自動產 docs。