node.js - 是否可以在不包装到函数/类中的情况下导出整个 Node.JS 模块?
问题描述
是否可以导出整个Node.JS
模块并具有以下功能:
- 从另一个模块导入这个模块
- 获取所有
methods
并attributes
设置到此模块中 - 我不想将此代码的任何部分从我的模块包装到函数/类中?
例如,我想创建一个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
使用模块的语法。
解决方案
是的,但是在 中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
}
推荐阅读
- reactjs - 如何使用 i18next 设置 RTL 翻译方向?
- java - 如何在 Junit 中分配枚举值?
- kotlin - 我在 kotlin 中放了令牌的地方
- python - 为什么在某些函数中可以访问全局变量而在其他函数中不能访问?
- mysql - 来自许多变量的 MySQL CONCAT_WS - 如何将查询限制为仅现有数据?
- sql-server - KC-SERVICES0089:无法运行计划任务 ClearExpiredClientInitialAccessTokens
- java - 应用程序被杀死时没有收到通知
- mysql - 在没有公共列的情况下连接 MYSQL 中的表
- python - python:带有简单ODE的pyABC-实例str和int之间不支持回溯错误<=
- elasticsearch - 弹性搜索重新索引。选择嵌套字段