javascript - 不能要求在同一文件夹中按索引导出对象
问题描述
这是示例应用程序:https ://codesandbox.io/s/gracious-bash-g7gg2
场景:
- 我可以在 exec.js 中调用 func1 和 func2
- 我可以通过这种方式调用
func2()
内部导入:func1()
const func2 = require('./func2')
- 我不能以这种方式调用
func2
内部func1()
导入:const { func2 } = require('./')
为什么相同的函数 import 在 exec.js 中有效而在 /src/func1.js 中无效?我收到“func2 不是函数”
解决方案
in the last scenario, you are requiring no file at all. It's like getting a function out of tin air.
Also, the syntax const { func2 }
is importing an exported property of an object to a variable through object destructuring. In your case, you are exporting an anonymous function. There is no property func2
to import.
if you wish to import func2
using the const { func2 } = require('./func2')
, you need to export that from func2
:
module.exports = {
func2: () => {
console.log("func2");
}
}
推荐阅读
- android - 我是否需要 FCM 高优先级消息才能在打盹模式下将更改推送到 Firestore 侦听器?
- c++ - 为什么在递归中使用循环会产生意想不到的结果?
- swift - 当 url 不是图像时,使用 AlamoFireImage 未捕获的 NSException 类型异常
- ios - 照片编辑扩展 - 将图像还原为原始图像
- c# - 替换问题
- ios - iOS - 未设置网络视图 cookie
- git - git cherry-pick {commit-hash} 做什么?
- python - 使用 Apache Beam 以 CSV 格式将 BigQuery 结果写入 GCS
- javascript - 聚合物 - bubbleEvent 不是函数
- android - Android MVVM BindingClass 不生成 ViewModel 的完整路径