【问题标题】:Is it possible to export the whole Node.JS module without wrapping into a function/class?是否可以在不包装到函数/类中的情况下导出整个 Node.JS 模块?
【发布时间】:2020-10-02 10:02:18
【问题描述】:

是否可以导出整个Node.JS模块并具有以下功能:

  1. 从另一个模块导入此模块
  2. 将所有methodsattributes 设置到此模块中
  3. 不想将此代码的任何部分从我的模块包装到函数/类中?

例如,我想创建一个REST.js 模块,它具有以下属性和方法:

let a = 10
let b = 20
const funcA = (x) => {
//functionA code
}
const funcB = (x, y) => {
//functionB code
}

这个模块需要使用一些语法导入app.js,这使我能够使用以下API(或类似的)从REST.js获取属性和使用方法:

const REST = require('REST')

//get attributes
console.log(REST.a)
console.log(REST.b)

//use methods

let resA = REST.funcA(10)
let resB = REST.funcB(10, 20)

总而言之,想知道有没有类似Python的语法使用模块。

【问题讨论】:

  • 随便module.exports.funcA = (x) => ..., module.exports.funcB = (x,y) => ...
  • @slebetman,不幸的是,这不方便。我需要使用一个简短的命令导出具有所有属性和方法的整个模块。在 Python 中,我什至不需要使用 module.exports,它会自动完成。
  • Node.js 不是 Python。类似地,Python 不能导出像 go 这样的函数,其中模块只导出大写函数,但小写函数会自动隐藏,因为 Python 不是 go

标签: node.js module.exports


【解决方案1】:

是的,但是在NodeJS 中,您必须像这样显式导出variables/functions

let a = 10
let b = 20
const funcA = (x) => {
//functionA code
}
const funcB = (x, y) => {
//functionB code
}

module.exports = {
  a,
  b,
  funcA,
  funcB
}

【讨论】:

  • 真的必须吗?有没有类似 module.export = * 的技巧?
  • 没有,据我所知
猜你喜欢
  • 2017-08-03
  • 2018-09-21
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
相关资源
最近更新 更多