chapter six

6 JavaScript’s module system

 

This chapter covers

  • Programmatic module patterns
  • Immediately-Invoked Function Expressions (IIFEs)
  • The ECMAScript Module syntax and the new .mjs extension
  • Dynamic vs static module systems
  • Tree shaking and dead code elimination
  • Principles of segregation and orthogonality

“Modular programming… removed limitless files”

Robert C. Martin (Uncle Bob)

The world of JavaScript development is changing frantically and the part of the language undergoing most of the change is its module system.

In these days of modern application development, we take the notion of modular programming for granted. The practice of breaking up our applications into different files and then linking them back together is already second nature to us. We don’t do this to avoid getting blisters in our fingers from endless scrolling, as Uncle Bob points out, we do this so that we can reason about and evolve different parts of our applications separately and 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 ECMAScript Modules basics

6.4.1 Path specifiers

6.4.2 Exporting

6.4.3 Importing

6.4.4 A new extension in town

6.5 Import patterns

6.5.1 Factory function

6.5.2 Builder pattern

6.6 Benefits of ESM

6.6.1 Dead code elimination and tree-shaking

6.6.2 Faster property lookups and checked variables

6.6.3 Type friendly

6.7 Segregated, orthogonal design using ESM

6.7.1 Segregated Architecture

6.7.2 Orthogonal Architecture

6.7.3 A segregated, orthogonal architecture

6.8 Summary