ES6 中 想要 export 一个对象的解构,要怎么操作?

2018-12-14 20:53:09 +08:00
 Shook

假设我有一个对象

const human = {
    talk,
    sleep,
    eat,
};

现在我想要在另一个 js 文件中引入这个对象中的方法,就像下面这样。

import { eat, talk } from './human';

那么我的 export 语句该怎么写呢? 之前用 module.exports 语句是可以实现的,但听说混用不太好。

module.exports = human;
9002 次点击
所在节点    JavaScript
16 条回复
des
2018-12-14 20:58:53 +08:00
export default human
这样?
qq1009479218
2018-12-14 21:02:11 +08:00
module.exports = human; 没问题啊,export default human 我知道 ts 这样用
cyril4free
2018-12-14 21:03:29 +08:00
module.exports 和 export default 输出都是 human 对象,想直接解构用 就 export const talk 这样用的时候就是
import { talk } from './human'
sxlzll
2018-12-14 21:06:05 +08:00
weixiangzhe
2018-12-15 00:12:24 +08:00
所以怎么整? 我今天也想这样来着,
weixiangzhe
2018-12-15 00:17:23 +08:00
tyrealgray
2018-12-15 00:17:44 +08:00
请认真看文档
Shook
2018-12-15 00:24:19 +08:00
@weixiangzhe
如果你想要 export 的对象,里面的属性是写死的话,就可以直接:
export default { eat: human.eat, sleep: human.sleep };

但如果你想要实现的和我的一样,是希望 export 能够不要关心 human 里面有什么属性,可以结合 commonjs:
module.exports = human;

这样的话,就能够使用 import { eat, sleep } 来引入了。
不过有一个问题,我在写 vue 的时候,是需要改 babel.config.js 才能这么做的。所以我才想要试着只用 ES6 来尝试这个效果,而不是混用。
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 } 手动指定。
noe132
2018-12-15 00:51:55 +08:00
如果使用 commonjs module,就可以随便操作。因为模块是运行时的
如果用 esmodule,就不允许存在不确定的 import export,不符合 esmodule 可以被静态分析的定义,自然就会报错
beyoung
2018-12-15 10:22:27 +08:00
直接 export 对象就可以了 export const human ={}

另外你 import 的时候 这个 js 的名称要是 human.js
Sparetire
2018-12-15 11:38:50 +08:00
无解, #9 是正解, export 是静态的
haiyang5210
2019-06-16 18:18:15 +08:00
@noe132 试了下为啥 export { xxx: a.xxx, yyy:a.yyy } 这种也会提示冒号是 非法字符呢
noe132
2019-06-17 00:06:21 +08:00
@haiyang5210 建议看文档。
export { a as b }
serge001
2019-10-15 14:08:13 +08:00
我是这样写的:
export function talk () {}
export function sleep() {}
export fucntion eat() {}

export default human
kcetry
2020-01-30 22:18:17 +08:00
export = human

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/517685

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX