How to import everything exported from a file with ES2015 syntax? Is there a wildcard? How to import everything exported from a file with ES2015 syntax? Is there a wildcard? javascript javascript

How to import everything exported from a file with ES2015 syntax? Is there a wildcard?


You cannot import all variables by wildcard for the first variant because it causes clashing variables if you have it with the same name in different files.

//a.jsexport const MY_VAR = 1;//b.jsexport const MY_VAR = 2;//index.jsimport * from './a.js';import * from './b.js';console.log(MY_VAR); // which value should be there?

Because here we can't resolve the actual value of MY_VAR, this kind of import is not possible.

For your case, if you have a lot of values to import, will be better to export them all as object:

// reducers.jsimport * as constants from './constants'console.log(constants.MYAPP_FOO)


Is there a syntax for the first variant,

No.

or do you have to either import each thing by name, or use the wrapper object?

Yes.


well you could import the object, iterate over its properties and then manually generate the constants with eval like this

import constants from './constants.js'for (const c in constants) {  eval(`const ${c} = ${constants[c]}`)}

unfortunately this solution doesn't work with intellisense in my IDE since the constants are generated dynamically during execution. But it should work in general.