首页 > 解决方案 > 是否可以在不包装到函数/类中的情况下导出整个 Node.JS 模块?

问题描述

是否可以导出整个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使用模块的语法。

标签: node.jsmodule.exports

解决方案


是的,但是在 中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
}

推荐阅读