javascript - 导出 Node.js 模块

标签 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模块吗?

最佳答案

仅在某处(例如在模块 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('...');

关于javascript - 导出 Node.js 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45284639/

相关文章:

javascript - 连接到远程 SSH 服务器(通过 Node.js/html5 控制台)

javascript - 逐步使用 Node.js 创建自定义应用程序

ruby require_relative 给出 LoadError : cannot infer basepath inside IRB

javascript - webpack 包中的必需模块未定义

ruby - 只加载 Ruby 中正在使用的类?

javascript - 需要 JavaScript 函数才能在 textarea 更改时运行

javascript - vscode 将行移到 block 快捷键上方

java - GWT 和 REST (jax-rs)

node.js - 用数据编译 gulp-jade

javascript - globbing - 匹配某些文件扩展名但不匹配其他文件扩展名的正确方法