Unit 4. Modules

 

Until recently, most front-end applications followed the same paradigm for using libraries: exposing globals. For example, if someone wanted to use jQuery (https://jquery.com) in a project, they would need to go to jQuery’s website, download either jquery.js or jquery.min.js, add it to their projects’s js or vendor folder, and then include a <script> tag importing the library into their application. This was not ideal, because it required modules to export themselves using global variables that could potentially collide with other global variables. It also required dependencies to be included before any library that relied on them or there would be an error.

Modules solve these problems by allowing scripts to be included by a module loader. The modules themselves can specify and load their dependencies, and thus relieve the application author from having to manage them.

Modules allow for dividing large amounts of code into small, cohesive units. Each module is contained in its own file. Anything in the file that isn’t exported is private, without needing to be wrapped in an immediately invoked function expression (IIFE) to create a private scope. Because the code inside a module doesn’t attach anything to the global namespace, any code outside of the module must explicitly import what it needs from the module in order to gain a reference to it.