ES6 export all values from object
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
Which is not dynamic.
Is it possible to export all values from an object?
I can't really recommend this solution work-around but it does function. Rather than exporting an object, you use named exports each member. In another file, import the first module's named exports into an object and export that object as default. Also export all the named exports from the first module using export * from './file1';
values/value.js
let a = 1;
let b = 2;
let c = 3;
export {a, b, c};
values/index.js
import * as values from './value';
export default values;
export * from './value';
index.js
import values, {a} from './values';
console.log(values, a); // {a: 1, b: 2, c: 3} 1
Does not seem so. Quote from ECMAScript 6 modules: the final syntax:
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).
I just had need to do this for a config file.
var config = {
x: "CHANGE_ME",
y: "CHANGE_ME",
z: "CHANGE_ME"
}
export default config;
You can do it like this
import { default as config } from "./config";
console.log(config.x); // CHANGE_ME
This is using Typescript mind you.
try this ugly but workable solution:
// use CommonJS to export all keys
module.exports = { a: 1, b: 2, c: 3 };
// import by key
import { a, b, c } from 'commonjs-style-module';
console.log(a, b, c);