javascript - What qualifies as being a dynamic export in ES6
2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址:https://cloud.tencent.com/act/cps/redirect?redirect=1062
2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址: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).
|
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
|
相关阅读排行
- 1Chapter 8 Dynamic Documents with Javascript
- 2grails的Dynamic Javascript Plugin介绍
- 3Javascript 面向对象编程动态原型方法(Dynamic prototype method)
- 4Cleaning your website with Ajax - Creating Next-Generation, Highly Dynamic, Off-line Capable Web Applications with HTML and JavaScript