【问题标题】:module.exports all the functions within a js filemodule.exports js文件中的所有函数
【发布时间】:2020-11-02 22:58:49
【问题描述】:

我想导出一个 JS 文件中的所有函数,而不在 module.exports 中单独指定要导出的函数

例子

function test1() {
  // do something
}
function test2() {
  // do something
}
function test3() {
  // do something
}

module.exports = {
  test1,
  test2,
  test3
}

【问题讨论】:

  • 不要认为这是可能的 - 这是,出口应该是明确的
  • 正如它所写的那样工作正常,但是是的,您需要显式导出方法、类等。

标签: javascript node.js syntax


【解决方案1】:

无法自动导出文件中的所有函数,因为无法枚举模块范围内的所有函数。 Javascript 不提供迭代函数范围内声明的所有变量或函数的方法。

相反,您可以将所有函数声明为某个对象的属性,然后枚举该对象上的所有属性并将它们分配给导出,或者直接导出该对象。

【讨论】:

    【解决方案2】:

    我不知道有一种方法可以自动导出文件中的所有功能,但如果您只是在寻找删除样板的方法,您可以直接在导出下定义它们:

    module.exports = {
        test1: function test1() { /* code */ },
        test2: function test2() { /* code */ },
        test3: function test3() { /* code */ }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2012-05-14
      • 2020-05-04
      • 2019-09-03
      相关资源
      最近更新 更多