Exporting a module Node.js
本问题已经有最佳答案,请猛点这里访问。
假设我有一个名为mainmodule.js的模块,它包含语句。
1 | var helper_formatModule = require('/formatModule.js'); |
在formatmodule.js中,我还有一个语句,
1 | var helper_handleSentences = require('/handleSentences.js'); |
如果我的原始模块mainmodule.js需要handlesences.js模块中定义的函数,它是否能够访问这些函数?也就是说,如果它导入了格式模块(一个具有handlesEntences的模块),那么它是否可以访问这些模块?还是需要直接导入handlesences.js模块?
仅在某个地方(例如模块B中)需要模块A并不能使其他模块中的功能可访问。通常,在模块B中甚至无法访问它们。
要从另一个模块访问函数(或任何值),另一个模块必须导出它们。以下情况将不起作用:
1 2 3 | // module-a.js function firstFunction () {} function secondFunction () {} |
1 2 3 4 5 6 | // module-b.js var helper_handleSentences = require('/handleSentences.js'); // do something with 'helper_handleSentences' module.exports = function (a) { return helper_handleSentences(a); } |
如你所见,
在你的情况下,你可以
1。需要1 2 3 4 5 6 7 8 9 | // 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; |
1 2 3 4 5 6 | // formatModule.js var helper_handleSentences = require('/handleSentences.js'); // do something with 'helper_handleSentences' module.exports = function (a) { return helper_handleSentences(a); }; |
1 2 3 4 | // mainModule.js var helper_handleSentences = require('/handleSentences.js'); var helper_formatModule = require('/formatModule.js'); // do something with 'helper_handleSentences' and 'helper_formatModule' |
2。将两个模块的导出值合并到一个对象中
1 2 3 4 5 6 7 8 9 | // 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; |
1 2 3 4 5 6 7 8 9 10 | // 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 }; |
1 2 3 4 5 | // mainModule.js var helper_formatModule = require('/formatModule.js'); // use both functions as methods helper_formatModule.handleSentences(); helper_formatModule.format('...'); |