6 ECMAScript Modules

 

This chapter covers

  • Evaluating programmatic module patterns
  • Reviewing Immediately Invoked Function Expressions (IIFEs)
  • Introducing the ECMAScript Module syntax and the new .mjs extension
  • Comparing dynamic and static module systems
  • Using tree-shaking and dead-code elimination

Scope is like oxygen to a programmer. It’s everywhere. You often don’t even think about it. But when it gets polluted . . . you choke.

—David Herman (Effective JavaScript)

The world of JavaScript development is changing frantically, and the part of the language that has undergone the most change is its module system.

In modern application development, we take the notion of modular programming for granted. The practice of breaking our applications into different files and then recombining them is already second nature to us. We don’t do these things to avoid getting blisters on our fingers from endless scrolling; we do them so that we can reason about and evolve different parts of our applications separately without fear of breaking others.

6.1 Past state of affairs

6.2 Module patterns

6.2.1 Object namespaces

6.2.2 Immediately Invoked Function Expressions (IIFEs)

6.2.3 IIFE mixins

6.2.4 Factory functions

6.3 Static vs. dynamic module systems

6.4 ESM basics

6.4.1 Path specifiers

6.4.2 Exporting

6.4.3 Importing

6.4.4 A new extension in town

6.5 Benefits of ESM for tooling

6.5.1 Dead-code elimination and tree-shaking