Node.js 模块是一种可以发布到 npm 的 封装。
🌐 Node.js modules are a type of package that can be published to npm.
🌐 Overview
package.json 文件🌐 Create a package.json file
package.json 文件,在命令行中,在你的 Node.js 模块的根目录下,运行 npm init:
name 和 version),以及 main 字段:
name:你的模块的名称。version:初始模块版本。我们建议遵循 语义化版本控制指南 并从 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
重要: 发布到 npm 需要以下条件之一:
欲了解更多信息,请参阅 npm 关于发布包时要求两步验证的文档。
🌐 For more information, see the npm documentation on requiring 2FA for package publishing.
在命令行上,在项目目录之外创建一个新的测试目录。
mkdir test-directory
切换到新目录:
cd /path/to/test-directory
在测试目录中,安装你的模块:
npm install <your-module-name>
在测试目录中,创建一个 test.js 文件,该文件需要你的模块并以方法的形式调用你的模块。
在命令行中,运行 node test.js。发送到 console.log 的消息应当显示出来。
🌐 Resources