Node.js 模块是一种可以发布到 npm 的 封装

🌐 Node.js modules are a type of package that can be published to npm.

概述

🌐 Overview

  1. 创建一个 package.json 文件
  2. 创建在你的模块被其他应用调用时将加载的文件
  3. 测试你的模块

创建一个 package.json 文件

🌐 Create a package.json file

  1. 要创建一个 package.json 文件,在命令行中,在你的 Node.js 模块的根目录下,运行 npm init
  2. 请填写必填字段(nameversion),以及 main 字段:

有关 package.json 文件的更多信息,请参见 “创建 package.json 文件”。

🌐 For more information on package.json files, see "Creating a package.json file".

创建另一个应用需要你的模块时将加载的文件

🌐 Create the file that will be loaded when your module is required by another application

创建一个与你在 main 字段中提供的名称相同的文件。在该文件中,将一个函数作为 exports 对象的属性添加。这样其他代码就可以使用该函数了:

🌐 Create a file with the same name you provided in the main field. In that file, add a function as a property of the exports object. This will make the function available to other code:

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

测试你的模块

🌐 Test your module

  1. 将你的包发布到 npm:

重要: 发布到 npm 需要以下条件之一:

  • 你的账户已启用双重身份验证 (2FA),或者
  • 启用绕过双重身份验证 (2FA) 的细粒度访问令牌

欲了解更多信息,请参阅 npm 关于发布包时要求两步验证的文档。

🌐 For more information, see the npm documentation on requiring 2FA for package publishing.

  1. 在命令行上,在项目目录之外创建一个新的测试目录。

    mkdir test-directory
  2. 切换到新目录:

    cd /path/to/test-directory
  3. 在测试目录中,安装你的模块:

    npm install <your-module-name>
  4. 在测试目录中,创建一个 test.js 文件,该文件需要你的模块并以方法的形式调用你的模块。

  5. 在命令行中,运行 node test.js。发送到 console.log 的消息应当显示出来。

资源

🌐 Resources