我已经阅读了 NodeJS 站点上的详细信息:https://nodejs.org/api/modules.html .我不明白模块是如何工作的,创建模块的最少步骤是什么,以及 npm 如何帮助我。
如何创建模块?
如何使用模块?
放在 npm 上是什么意思?
Note: this is a self answered question, with the purpose of sharing knowledge as a canonical.
最佳答案
您可以使用一行代码创建一个 NodeJS 模块:
//mymodule.js
module.exports = 3;
然后你可以加载模块,使用require:
//app.js
require('./mymodule.js')
我添加了“./”,因为它是一个文件的模块。我们稍后会介绍它。
现在,如果你这样做:
var mymodule = require('./mymodule.js');
console.log(mymodule); // 3
您可以用函数替换数字 3,例如:
//mymodule.js:
module.exports = function () {
console.log('function inside the module');
};
然后就可以使用了:
var mymodule = require('./mymodule.js');
mymodule();
私有(private)变量:
您在 A 模块中定义的每个变量都将仅在其中定义:
//mymodule.js
var myPrivateVariable = 3;
publicVariable = 5; // Never user global variables in modules
//It's bad-pracrtice. Always add: var.
module.exports = function() {
// Every function of the module can use the private variables
return myPrivateVariable++
};
//app.js
var mymodule = require('./mymodule.js');
console.log(mymodule()); // return 3
console.log(mymodule()); // return 4
重用模块:
关于 NodeJS 模块,您需要了解的另一件事是,如果您两次使用相同的模块(需要它),它将返回相同的实例,它不会运行两次。
例如:
//app.js
var mymodule1 = require('./mymodule.js');
var mymodule2 = require('./mymodule.js');
console.log(mymodule1()); //return 3
console.log(mymodule2()); //return 4 (not 3)
console.log(mymodule1()); //return 5
正如您在下面的示例中看到的,该私有(private)变量在模块的所有实例之间共享。
模块包
如果你的模块包含多个文件,或者你想与其他人共享模块,你必须在单独的文件夹中创建模块,并为模块创建一个 package.json
文件。
npm init
将为您创建 package.json 文件。
对于模块,有 3 个必需部分:
package.json
{
"name" : "You module name",
"version" : "0.0.3"
}
现在,您可以使用 npm publish
发布模块。我建议您也将所有模块发布到 github,然后模块将连接到您的 github 页面。
您发布到 NPM 的内容将可供所有人访问。所以永远不要发布包含私有(private)数据的模块。为此,您可以使用私有(private) npm 模块。
后续步骤
模块可以返回多个函数或一个变量。请参阅我们返回对象的示例。
module.exports.a = function() {
// ..
};
module.exports.b = function() {
// ..
};
// OR
myObj = {
a:3,
b:function() {
return this.a;
}
};
module.exports = myObj;
更多信息:
- Read about package.json files
- Versioning in you modules best practice
- More best practive for NodeJS modules
- Private modules, using private npm
相关问题:
关于node.js - 如何创建 NodeJS 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35888383/