ES6 从对象导出所有值 [英] ES6 export all values from object
问题描述
假设我有一个模块 (./my-module.js
),它有一个对象,它应该是它的返回值:
Say I have a module (./my-module.js
) that has an object which should be its return value:
let values = { a: 1, b: 2, c: 3 }
// "export values" results in SyntaxError: Unexpected token
所以我可以像这样导入它们:
So I can import them like:
import {a} from './my-module' // a === 1
import * as myModule from './my-module' // myModule.a === 1
我发现的唯一方法是对导出进行硬编码:
The only way I found is by hard coding the exports:
export let a = values.a
export let b = values.b
export let c = values.c
// or:
export let {a, b, c} = values
这不是动态的.
是否可以从对象中导出所有值?
Is it possible to export all values from an object?
推荐答案
似乎并非如此.引用自 ECMAScript 6 模块:最终语法:
Does not seem so. Quote from ECMAScript 6 modules: the final syntax:
您可能想知道 - 如果我们可以简单地默认导出对象(如 CommonJS),为什么我们需要命名导出?答案是您不能通过对象强制执行静态结构并失去所有相关优势(在下一节中描述).
You may be wondering – why do we need named exports if we could simply default-export objects (like CommonJS)? The answer is that you can’t enforce a static structure via objects and lose all of the associated advantages (described in the next section).
这篇关于ES6 从对象导出所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!