ITKeyword,专注技术干货聚合推荐

注册 | 登录

javascript - What qualifies as being a dynamic export in ES6

itPublisher 分享于

2020腾讯云10周年活动,优惠非常大!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1040

2020阿里云最低价产品入口,含代金券(新老用户有优惠),
地址https://www.aliyun.com/minisite/goods

I hear that dynamic exports/imports are not allowed in es6.

This website Uses the example export default 5 * 7; as if it were a legal, static export. This seems reasonable since it clearly evaluates to the static value of 35, but I'm wondering what exactly qualifies as a static export now.

This Code uses export default Backbone.Router.extend({...}); as if it were a legal, static, export. This seems fishy to me as it seems like a dynamic export to me (exporting the result of a function call).

javascript ecmascript-6
|
  this question
asked Jan 27 '16 at 10:52 Kevin Wheeler 532 5 15

 | 

2 Answers
2

The second example only exports the result of the function call, which is static. The function is only called once, thus the result will always be the same on every import.

An Example to illustrate:

f.js

function f() {
    return 2 * Math.random();
}

export default f(); // Is called, before the export is defined. Result: 1.23543

i1.js

import f from 'f';

console.log(f); // 1.23543

i2.js

import f from 'f';

console.log(f); // 1.23543 as well

|
  this answer
answered Jan 27 '16 at 10:58 nils 7,104 1 17 39

 | 

All exports are static in ES6, that is, their exported name resolves to exactly one variable binding in the exporting module and this can be determined by a single look prior to evaluating of the module code.

A module cannot dynamically add or remove exports through execution of code, the list of exported names is fixed by the declaration.

Whether this variable holds a constant or the result of a function call doesn't matter, neither does whether it holds a primitive value or an object. It doesn't even need to be a constant, the content of the variable may change over time (see an example here).

All imports from import statements are static as well, which means that you can explore the dependency graph without executing any module code.

A dynamic import is done by an explicit call to the module loader. Such loads can depend on the control flow of the module, and may differ from run to run. The code needs to manually handle the asynchrony of the process and potential errors.


|
  this answer
edited Jan 27 '16 at 11:09 answered Jan 27 '16 at 10:59 Bergi 245k 24 291 432

 | 


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。