简体   繁体   English

用JavaScript导出动态名称

[英]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 ). 这在所谓的“树摇动”中具有巨大的优势,在“摇树”中 ,可以根据实际使用的内容有选择地导入代码(并且此功能由汇总器webpack之类的模块捆绑器使用 )。

This is the key way in which ES6 modules differ from commonjs . 这是ES6模块与commonjs不同的关键方式。 If you require a method from a library everything in the file is run, not only what you use. 如果您require库中的方法,则文件中的所有内容都会运行,而不仅仅是您使用的内容。 If you import a function from a library you (should) only get that function. 如果从库中import函数,则(应该)仅获得该函数。 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. ECMAScript 6为您提供了两全其美的优势:Node.js的同步语法以及AMD的异步加载。 To make both possible, ES6 modules are syntactically less flexible than Node.js modules: Imports and exports must happen at the top level. 为了使两者都实现,ES6模块在语法上不如Node.js模块灵活:导入和导出必须在顶层进行。 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. 此限制使ES6模块加载器可以静态分析模块导入了哪些模块,并在执行其主体之前加载它们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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