最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ecmascript 6 - Export dynamic name in Javascript - Stack Overflow

programmeradmin6浏览0评论

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

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());
Share Improve this question asked Mar 22, 2019 at 9:02 Jim JinJim Jin 1,5193 gold badges17 silver badges32 bronze badges 3
  • 2 Not without eval, why don't you just export an object with those named properties? – Ben Fortune Commented Mar 22, 2019 at 9:04
  • 2 Or better yet, just create a function that calls your fn with i – Ben Fortune Commented Mar 22, 2019 at 9:10
  • If I export an object with named props, I have to introduce the name of the object to the caller. Besides, these exports could be seperated in several files. – Jim Jin Commented Mar 22, 2019 at 9:36
Add a ment  | 

2 Answers 2

Reset to default 5

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 monjs. 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 "wele js"
}
[1,2,3,4].forEach(i =>fnCollection[`fn${i}`] = fn.bind(null, i.toString()));
export default fnCollection ;
发布评论

评论列表(0)

  1. 暂无评论