【问题标题】:Exporting a module Node.js [duplicate]导出模块 Node.js [重复]
【发布时间】:2017-12-30 06:41:07
【问题描述】:

假设我有一个名为 mainModule.js 的模块,其中包含该语句。

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

在formatModule.js里面,我也有一个说法,

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

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

【问题讨论】:

  • helper_formatModule 通常在 helper_handleSentences 中不可用,除非您正在导出。这是由于how closures work

标签: javascript node.js require


【解决方案1】:

仅在某处(例如,在模块 B 中)需要模块 A 不会使 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('...');

【讨论】:

  • 水晶。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 2016-09-20
  • 2021-08-21
  • 2019-10-28
  • 1970-01-01
相关资源
最近更新 更多