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:

  1. Module code automatically runs in strict mode, and there’s no way to opt-out of strict mode.
  2. 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.
  3. The value of this in the top level of a module is undefined.
  4. Modules don’t allow HTML-style comments within code (a leftover feature from JavaScript’s early browser days).
  5. Modules must export anything that should be available to code outside of the module.
  6. 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.