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

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

概述

¥Overview

  1. 创建 package.json 文件

    ¥Create a package.json file

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

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

  3. 测试你的模块

    ¥Test your module

创建 package.json 文件

¥Create a package.json file

  1. 要创建 package.json 文件,请在命令行中,在 Node.js 模块的根目录中运行 npm init

    ¥To create a package.json file, on the command line, in the root directory of your Node.js module, run npm init:

  2. 为必填字段(nameversion)以及 main 字段提供响应:

    ¥Provide responses for the required fields (name and version), as well as the main field:

    • name:你的模块的名称。

      ¥name: The name of your module.

    • version:初始模块版本。我们建议遵循 语义版本控制指南 并从 1.0.0 开始。

      ¥version: The initial module version. We recommend following semantic versioning guidelines and starting with 1.0.0.

有关 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:

    ¥Publish your package to npm:

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

    ¥On the command line, create a new test directory outside of your project directory.

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

    ¥Switch to the new directory:

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

    ¥In the test directory, install your module:

    npm install <your-module-name>
  5. 在 test 目录中,创建一个 test.js 文件,该文件需要你的模块并将你的模块作为方法调用。

    ¥In the test directory, create a test.js file which requires your module and calls your module as a method.

  6. 在命令行上,运行 node test.js。应该会出现发送到 console.log 的消息。

    ¥On the command line, run node test.js. The message sent to the console.log should appear.

资源

¥Resources

npm 中文网 - 粤ICP备13048890号