What are Modules?
Modules are JavaScript files that are loaded in a different mode (as opposed to scripts, which are loaded in the original way JavaScript worked). This different mode is necessary because modules have very different semantics than scripts:
- Module code automatically runs in strict mode, and there’s no way to opt-out of strict mode.
- Variables created in the top level of a module aren’t automatically added to the shared global scope. They exist only within the top-level scope of the module.
- The value of
this
in the top level of a module isundefined
. - Modules don’t allow HTML-style comments within code (a leftover feature from JavaScript’s early browser days).
- Modules must export anything that should be available to code outside of the module.
- Modules may import bindings from other modules.
These differences may seem small at first glance, but they represent a significant change in how JavaScript code is loaded and evaluated, which I will discuss over the course of this chapter. The real power of modules is the ability to export and import only bindings you need, rather than everything in a file. A good understanding of exporting and importing is fundamental to understanding how modules differ from scripts.