注册 | 登录

javascript - What qualifies as being a dynamic export in ES6

itPublisher 分享于



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

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:


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

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


import f from 'f';

console.log(f); // 1.23543


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









您的注册邮箱: 修改

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