Chapter 10. Modular JavaScript Design Patterns

In the world of scalable JavaScript, when we say an application is modular, we often mean it’s composed of a set of highly decoupled, distinct pieces of functionality stored in modules. Loose coupling facilitates easier maintainability of apps by removing dependencies where possible. When implemented efficiently, it becomes pretty easy to see how changes to one part of a system may affect another.

In the earlier chapters, we covered the importance of modular programming and the modern way of implementing modular design patterns. While ES2015 introduced native modules to JavaScript, writing modular JavaScript was still possible before 2015.

In this section, we will look at three formats for modular JavaScript using classic JavaScript (ES5) syntax: Asynchronous Module Definition (AMD), CommonJS, and Universal Module Definition (UMD). To learn more about JavaScript modules, please refer to Chapter 5, which covers ES2015+ syntax for module imports, exports, and more.

A Note on Script Loaders

It isn’t easy to discuss AMD and CommonJS modules without talking about script loaders. Script loading was a means to a goal. Modular JavaScript could be implemented only using compatible script loaders.

Several great loaders were available for handling module loading in the AMD and CommonJS formats, but I personally preferred RequireJS and curl.js.

AMD

The AMD format was introduced as a proposal for defining modules in which both the module and ...

Get Learning JavaScript Design Patterns, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.