首页 > 解决方案 > 不能要求在同一文件夹中按索引导出对象

问题描述

这是示例应用程序:https ://codesandbox.io/s/gracious-bash-g7gg2

场景:

为什么相同的函数 import 在 exec.js 中有效而在 /src/func1.js 中无效?我收到“func2 不是函数”

标签: javascriptnode.js

解决方案


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");
    }
}

推荐阅读