假设我有一个名为 mainModule.js 的模块,其中包含该语句。
var helper_formatModule = require('/formatModule.js');
在 formatModule.js 里面,我也有一个声明,
var helper_handleSentences = require('/handleSentences.js');
如果我的原始模块 mainModule.js 需要在 handleSentences.js 模块中定义的函数,它是否能够访问它们?即如果它导入了 formatModule,一个具有 handleSentences 的模块,它是否可以访问那些?还是我需要直接导入 handleSentences.js 模块?
仅在某处(例如,在模块 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
保存默认导出值,即一个空对象。
在你的情况下,你可以
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'
// 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('...');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句