前言

面給出一份「從 0 到 1」把 Node.js 代碼打包併發布為公共 npm 包的完整流程,全部步驟均來自 2024-2025 年最新社區實踐,可直接照做。

(如只想打綠色可執行文件不發佈,可跳到最後「附:PKG 綠色可執行包」小節)


一、前置準備

  1. 安裝 Node.js ≥ 14(推薦 18 LTS)
  2. 註冊 npm 賬號 → https://www.npmjs.com/signup
  3. 本地登錄

1

2


npm login               # 按提示輸入賬號、密碼、郵箱

npm whoami              # 驗證是否登錄成功




二、創建與編碼

  1. 新建文件夾並初始化

1

2

3


mkdir my-utils          # 包名僅作示例

cd my-utils

npm init -y             # 生成默認 package.json



  1. 修改 package.json(關鍵字段)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19


{

"name": "my-utils",          // 全網唯一,可先去 npm 搜索確認

"version": "1.0.0",

"description": "常用工具函數",

"main": "dist/index.js",     // CommonJS 入口

"module": "dist/index.mjs",  // ESModule 入口(可選)

"files": ["dist"],           // 只發布 dist 目錄

"scripts": {

"build": "tsup src/index.ts --format cjs,esm --dts",

"prepublishOnly": "npm run build"

},

"keywords": ["utils", "tool"],

"author": "your-name <you@example.com>",

"license": "MIT",

"repository": {

"type": "git",

"url": "https://github.com/yourname/my-utils.git"

}

}



  1. 業務代碼

1

2


src

└── index.ts



示例 src/index.ts

1

2


export const sleep = (ms: number) =>

  new Promise<void>(r => setTimeout(r, ms));


  1. 安裝打包工具(零配置,2024 最流行)

1


npm i -D tsup typescript @types/node




三、一鍵構建

1


npm run build


生成 dist/ 目錄,裏面同時出現

  • index.js → CommonJS
  • index.mjs → ESModule
  • index.d.ts → 類型聲明


四、本地“白嫖”測試(可選)

  1. 把包鏈到全局

1


npm link



  1. 在任意項目裏

1


npm link my-utils



  1. 使用

1

2


const { sleep } = require('my-utils');

(async () => { await sleep(1000); console.log('ok'); })();




五、發佈公共包

  1. 確保包名全局唯一(去 https://www.npmjs.com/search 搜一下)
  2. 發佈

1


npm publish --access public



成功後會收到 npm 官方郵件;隨後任何人可

1


npm i my-utils



六、常見踩坑提醒

表格

複製

問題

解決方案

名字重複

提前搜索,或加 scope: @yourname/utils 發佈時同樣 npm publish --access public

私有包收費

公共包不要用 @scope/pkg 除非加 --access public

忘記構建

用 prepublishOnly 鈎子,每次 npm publish 前自動 npm run build

二進制文件

如果包內含原生 .node 文件,需在不同平台分別 prebuild 或使用 @mapbox/node-pre-gyp


附:PKG 綠色可執行包(可選,不發佈 npm 也能用)

  1. 安裝

1


npm i -g pkg



  1. 在 package.json 裏增加

1

2

3

4

5


"bin": "dist/cli.js",

"pkg": {

"targets": ["node18-win-x64", "node18-linux-x64", "node18-macos-x64"],

"outputPath": "release"

}



  1. 打包

1


pkg . --compress Brotli



得到 release/ 目錄下的綠色可執行文件,無 Node 環境也能運行。

完成!現在你已經同時擁有

  • 一個可 npm i xxx 安裝的公共包
  • 一份可選的綠色可執行文件用於離線分發。

如需繼續補充「CI 自動發佈」「語義化版本」「雙模塊(CommonJS + ESM)兼容」等進階主題。