导出默认vs模块。导出差异 [英] export default vs module.exports differences
问题描述
这有效:
import {bar} from './foo';
bar();
// foo.js
module.exports = {
bar() {}
}
这可行:
import foo from './foo';
foo.bar();
// foo.js
export default {
bar() {}
}
那为什么不起作用?
import {bar} from './foo';
bar();
// foo.js
export default {
bar() {}
}
它抛出 TypeError:(0,_foo.bar)不是一个函数
。
推荐答案
当您拥有
export default {
bar() {}
}
导出的实际对象具有以下形式:
The actual object exported is of the following form:
exports: {
default: {
bar() {}
}
}
执行简单导入时(例如, import foo from './foo';
)实际上是在导入中获取默认对象(即 exports.default
)。当您运行babel编译为ES5时,这一点将变得显而易见。
When you do a simple import (e.g., import foo from './foo';
) you are actually getting the default object inside the import (i.e., exports.default
). This will become apparent when you run babel to compile to ES5.
当您尝试导入特定功能时(例如, import {bar} from './foo';
),根据您的情况,您实际上是在尝试获取 exports.bar
而不是 exports.default.bar
。因此,为什么未定义bar函数。
When you try to import a specific function (e.g., import { bar } from './foo';
), as per your case, you are actually trying to get exports.bar
instead of exports.default.bar
. Hence why the bar function is undefined.
当您只有多个出口时:
export function foo() {};
export function bar() {};
您最终将拥有此对象:
exports: {
foo() {},
bar() {}
}
,因此从'./foo'导入{bar};
将起作用。与 module.exports
类似的情况是,您实际上是按照上述方式存储导出对象的。因此,您可以导入bar函数。
And thus import { bar } from './foo';
will work. This is the similar case with module.exports
you are essentially storing an exports object as above. Hence you can import the bar function.
我希望这已经足够清楚了。
I hope this is clear enough.
这篇关于导出默认vs模块。导出差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!