节点js中的exports.install是什么?
问题描述:
嗨,我发现framework他们在这里使用了很多这种模式。节点js中的exports.install是什么?
exports.install = function(){
//code
}
但通常你看到这个模式中的NodeJS
module.exports = {
//code
}
这是同样的事情,或者这是什么东西?
答
exports
是对应于module.exports
之前的任何对象。我认为这是由于一些遗留代码造成的,但基本上人们使用module.exports
如果他们想用自己的对象或函数替换整个对象,而如果他们只想从模块中挂起函数,则使用exports
。这是一个有点混乱在第一,但本质上exports.install
只是意味着调用代码会做这样的事情:
const mod = require('that-module');
mod.install(params, callback); // call that function
你看这个框架可能是使用它作为一个引导过程的一部分,据我所知它不对节点引擎本身具有重要意义。
答
是的,这是一回事。您可以使用2种方式之一来设置您的代码。
不同的是memory
。他们指向相同的记忆。你可以认为exports
像一个变量,你不能用这种方式来导出模块:
鉴于此模块:
// test.js
exports = {
// you can not use this way to export module.
// because at this time, `exports` points to another memory region
// and it did not lie on same memory with `module.exports`
sayHello: function() {
console.log("Hello !");
}
}
下面的代码将得到错误:TypeError: test.sayHello is not a function
// app.js
var test = require("./test");
test.sayHello();
// You will get TypeError: test.sayHello is not a function
您必须使用module.exports
导出模块的正确方法:
// test.js
module.exports = {
// you can not use this way to export module.
sayHello: function() {
console.log("Hello !");
}
}
// app.js
var test = require("./test");
test.sayHello();
// Console prints: Hello !
所以,它只是开发者的风格。