假设我有一个对象
const human = { talk, sleep, eat, };
现在我想要在另一个 js 文件中引入这个对象中的方法,就像下面这样。
import { eat, talk } from './human';
那么我的 export 语句该怎么写呢? 之前用 module.exports 语句是可以实现的,但听说混用不太好。
module.exports = human;
尝试了一些方法。
export default human;
上面的方法不能通过 import { eat } 拿到,于是尝试了下面的方法。
export default { ...human };
试着耍小聪明,但实验后确认上面的方法结果等同于第一种,又失败了。
for (let key in human) { if (human.hasOwnProperty(key)) export const [key] = human[key]; }
被逼得乱打一通,但export不能这么用,还是失败了。
![]() | 1 des 2018-12-14 20:58:53 +08:00 via Android export default human 这样? |
![]() | 2 qq1009479218 2018-12-14 21:02:11 +08:00 module.exports = human; 没问题啊,export default human 我知道 ts 这样用 |
![]() | 3 cyril4free 2018-12-14 21:03:29 +08:00 module.exports 和 export default 输出都是 human 对象,想直接解构用 就 export const talk 这样用的时候就是 import { talk } from './human' |
4 sxlzll 2018-12-14 21:06:05 +08:00 |
![]() | 5 weixiangzhe 2018-12-15 00:12:24 +08:00 所以怎么整? 我今天也想这样来着, |
![]() | 6 weixiangzhe 2018-12-15 00:17:23 +08:00 感觉需要用 dynamic export $export(xxx) https://medium.com/@WebReflection/Javascript-dynamic-import-export-b0e8775a59d4 |
![]() | 7 tyrealgray 2018-12-15 00:17:44 +08:00 via Android 请认真看文档 |
![]() | 8 Shook OP @weixiangzhe 如果你想要 export 的对象,里面的属性是写死的话,就可以直接: export default { eat: human.eat, sleep: human.sleep }; 但如果你想要实现的和我的一样,是希望 export 能够不要关心 human 里面有什么属性,可以结合 commonjs: module.exports = human; 这样的话,就能够使用 import { eat, sleep } 来引入了。 不过有一个问题,我在写 vue 的时候,是需要改 babel.config.js 才能这么做的。所以我才想要试着只用 ES6 来尝试这个效果,而不是混用。 |
![]() | 9 noe132 2018-12-15 00:50:03 +08:00 ![]() export default a 等同于 export { default: a } export 是不能使用解构的,因为 export 是静态的,结构是 runtime 的 你需要 export { xxx: a.xxx, yyy:a.yyy } 手动指定。 |
![]() | 10 noe132 2018-12-15 00:51:55 +08:00 ![]() 如果使用 commonjs module,就可以随便操作。因为模块是运行时的 如果用 esmodule,就不允许存在不确定的 import export,不符合 esmodule 可以被静态分析的定义,自然就会报错 |
![]() | 11 beyoung 2018-12-15 10:22:27 +08:00 via iPhone 直接 export 对象就可以了 export const human ={} 另外你 import 的时候 这个 js 的名称要是 human.js |
![]() | 12 Sparetire 2018-12-15 11:38:50 +08:00 无解, #9 是正解, export 是静态的 |
13 haiyang5210 2019-06-16 18:18:15 +08:00 |
![]() | 14 noe132 2019-06-17 00:06:21 +08:00 @haiyang5210 建议看文档。 export { a as b } |
15 serge001 2019-10-15 14:08:13 +08:00 我是这样写的: export function talk () {} export function sleep() {} export fucntion eat() {} export default human |
16 kcetry 2020-01-30 22:18:17 +08:00 export = human |