简体   繁体   中英

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());

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.

let fnCollection = {};
function fn(){
  return "welcome js"
}
[1,2,3,4].forEach(i =>fnCollection[`fn${i}`] = fn.bind(null, i.toString()));
export default fnCollection ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM