导出模块Node.js

时间:2017-07-24 15:33:43

标签: javascript node.js require

假设我有一个名为mainModule.js的模块,它具有该语句。

var helper_formatModule = require('/formatModule.js'); 

在formatModule.js中,我也有一个声明,

var helper_handleSentences = require('/handleSentences.js'); 

如果我的原始模块mainModule.js需要handleSentences.js模块中定义的函数,它是否能够访问它们?即如果它导入formatModule,一个具有handleSentences的模块,它是否可以访问那些?或者我需要直接导入handleSentences.js模块吗?

1 个答案:

答案 0 :(得分:1)

仅在某处需要模块A(例如,在模块B中)并不能使其他模块中的A功能可访问。通常情况下,它们甚至无法在模块B中访问。

要从其他模块访问功能(或任何值),其他模块必须导出它们。以下方案不起作用:

// module-a.js
function firstFunction () {}
function secondFunction () {}
// module-b.js
var helper_handleSentences = require('/handleSentences.js'); 
// do something with 'helper_handleSentences'
module.exports = function (a) {
  return helper_handleSentences(a);
}

如您所见,module-a.js并未导出任何内容。因此,变量a保存默认导出值,即空对象。

在您的情况下,您可以

1。需要mainModule.js

中的两个模块
// handleSentences.js
function doSomethingSecret () {
  // this function can only be accessed in 'handleSentences.js'
}
function handleSentences () {
  // this function can be accessed in any module that requires this module
  doSomethingSecret();
}
module.exports = handleSentences;
// formatModule.js
var helper_handleSentences = require('/handleSentences.js'); 
// do something with 'helper_handleSentences'
module.exports = function (a) {
  return helper_handleSentences(a);
};
// mainModule.js
var helper_handleSentences = require('/handleSentences.js');
var helper_formatModule = require('/formatModule.js'); 
// do something with 'helper_handleSentences' and 'helper_formatModule'

2。将两个模块的导出值合并为一个对象

// handleSentences.js
function doSomethingSecret () {
  // this function can only be accessed in 'handleSentences.js'
}
function handleSentences () {
  // this function can be accessed in any module that requires this module
  doSomethingSecret();
}
module.exports = handleSentences;
// formatModule.js
var helper_handleSentences = require('/handleSentences.js'); 
// do something with 'helper_handleSentences'
function formatModule (a) {
  return helper_handleSentences(a);
};
module.exports = {
  handleSentences: helper_handleSentences,
  format: formatModule
};
// mainModule.js
var helper_formatModule = require('/formatModule.js');
// use both functions as methods
helper_formatModule.handleSentences();
helper_formatModule.format('...');