仅在某个地方需要模块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
//此函数只能在“handlementes.js”中访问
//可以在需要此模块的任何模块中访问此功能
doSomethingSecret();
}
// 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('...');