> You can use module loaders to do exactly this (I believe, based on my
> understanding of CommonJS). It would look like:
>
> var ml = ... the desired module loader ...
> var a;
> if (someCondition) {
> a = ml.load("a1");
> } else {
> a = ml.load("a2");
> }
Correction: you have to use callbacks for dynamic loading:
var ml = ... the desired module loader ...
if (someCondition) {
ml.load("a1", useA);
} else {
ml.load("a2", useA);
}
function useA(a) {
...
}
Callbacks are the downside of dynamic loading, but that's the nature of
asynchronous I/O in ES -- it's a fact of life.
However, I would submit that at least in some cases you don't necessarily need
conditional loading. For example, if you'd like to choose between two different
exports from two different modules, you can load them both and conditionally
refer to one or the other:
module a1 = "a1";
module a2 = "a2";
var x;
if (someCondition) {
x = a1.foo;
} else {
x = a2.bar;
}
Obviously that doesn't cover all situations, but the design of simple modules
attempts to achieve a balance between the following:
- making it easy to load modules statically
- making modules compatible with static scoping
- making it possible (though admittedly less convenient) to load modules
dynamically
>> 2) What are the design decisions behind only allowing "module" and
>> "use" at the top level of a module?
>
> Modules are a statically scoped construct, and the implementation and
> the programmer can both statically tell where variables come from.
> This prevents modules from being dynamically created, except in the
> context of module loaders, as seen above.
Just to flesh this out a bit: simple modules were designed to make it possible
to import and export variables into lexical scope, and to be compatible with
checking valid imports and exports statically, as well as being able to check
for unbound variables statically. Including, for example, in the case where you
say
import M.*;
Moreover, they are designed to allow loading modules *without* having to use
callbacks, in the common case where they can be pre-loaded at compile-time.
Now, we could've gone further by adding a compile-time sub-language for doing
things like conditional loading, but we wanted to avoid the complexity of
bifurcating ES into a compile-time language separate from the run-time
language. If you want more complicated logic, our design requires you to do it
dynamically. Again, it's a trade-off: we could've made a more expressive static
module language, but I'm skeptical that its utility would be worth the
complexity it would introduce.
Dave
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss