Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export dynamic name in Javascript

Suppose we have to export a large amount of names.

export const fn0 = fn.bind(null, '0');
export const fn1 = fn.bind(null, '1');
...
export const fn999 = fn.bind(null, '999');

Is it possible to export dynamic names like the following?

// array is [0 to 999]
array.forEach(i => export const [`fn${i}`] = fn.bind(null, i.toString());
like image 389
Jim Jin Avatar asked Oct 22 '25 15:10

Jim Jin


2 Answers

Bluntly, no. And this is by design.

The module syntax is designed to be statically analysed. This means that it can be determined which modules are required by other modules without executing any code. This has huge benefits in so-called "tree shaking" where code can be selectively imported based on what is actually used (and this feature is used by module bundlers such as rollup and webpack).

This is the key way in which ES6 modules differ from commonjs. If you require a method from a library everything in the file is run, not only what you use. If you import a function from a library you (should) only get that function. You cannot do that if you have to run all of the code in order to find out what is exported.

to quote from here

ECMAScript 6 gives you the best of both worlds: The synchronous syntax of Node.js plus the asynchronous loading of AMD. To make both possible, ES6 modules are syntactically less flexible than Node.js modules: Imports and exports must happen at the top level. That means that they can’t be conditional, either. This restriction allows an ES6 module loader to analyze statically what modules are imported by a module and load them before executing its body.

like image 111
Euan Smith Avatar answered Oct 24 '25 04:10

Euan Smith


let fnCollection = {};
function fn(){
  return "welcome js"
}
[1,2,3,4].forEach(i =>fnCollection[`fn${i}`] = fn.bind(null, i.toString()));
export default fnCollection ;
like image 35
Boobalan Avatar answered Oct 24 '25 03:10

Boobalan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!