Node.js 模組是一種可以發佈到 npm 的套件

概述

  1. 建立 package.json 檔案
  2. 建立當您的模組被其他應用程式載入時將載入的檔案
  3. 測試您的模組

建立 package.json 檔案

  1. 若要建立 package.json 檔案,請在命令列中,於 Node.js 模組的根目錄執行 npm init
  2. 提供必要欄位(nameversion)的回應,以及 main 欄位:

有關 package.json 檔案的更多資訊,請參閱「建立 package.json 檔案」。

建立當您的模組被其他應用程式載入時將載入的檔案

在檔案中,將函式新增為 exports 物件的屬性。這將讓其他程式碼可以使用此函式

exports.printMsg = function() {
console.log("This is a message from the demo package");
}

測試您的模組

  1. 將您的套件發佈到 npm

  2. 在命令列中,在專案目錄外建立新的測試目錄。

    mkdir test-directory
  3. 切換至新目錄

    cd /path/to/test-directory
  4. 在測試目錄中,安裝您的模組

    npm install <your-module-name>
  5. 在測試目錄中,建立一個 test.js 檔案,它需要您的模組並呼叫您的模組作為方法。

  6. 在命令列中,執行 node test.js。傳送到 console.log 的訊息應該會出現。

資源