This video is available to students only

JS Modules

What are JS Modules, and how do they affect consumers of our code?

Writing our whole library in a single file makes it hard to find code, and vastly increases the chances of merge conflicts in Git. The next step is to separate code into separate files to improve maintainability and readability. In the early days of JavaScript having separate files meant we needed to have multiple script tags like <script src="myFile.js"></script> in our HTML to import each file. This was tedious because a new script tag would need to be added for each new file created. Another issue is some files are dependent on other files. So a function in file X would need to exist before it was called in file Y. Not only did we have to create new <script> tags for each new file, but the files had to the ordered correctly!

These issues lead to new module systems being introduced into the JavaScript community, such as AMD (Asynchronous Module Definition) and CJS (CommonJS). Only recently was ESM (ECMAScript Modules) introduced as a core JavaScript feature and final standard for modules.

CJS (CommonJS)#

CommonJS (CJS) modules were created to provide synchronous module handling in NodeJS. When a file needs to make code public, the CJS uses module.exports syntax. For example, if we were to export an add(a, b); function using CJS it would look like:

Importing code uses the require() syntax. To use add() in a separate file we use require() to point to the add.js file.

CJS is still heavily used in NodeJS programs, and while running code in NodeJS environments. For example, many build tools like Webpack (the webpack.config.js file) use module.exports syntax to define configuration files.

AMD (Asynchronous Module Definition)#

Asynchronous Module Definition (AMD) is a solution for loading dependencies asynchronously, which was popularized in a library called RequireJS. Code using AMD would look like:

define() is a function that takes an array of dependencies as the first argument. The second argument is a callback, a function called after the dependencies are loaded, that provides access to the loaded modules. AMD is used less as ECMAScript Modules and Universal Module Definition have become more popular, but as a library owner, it's important to be aware of it.

 

This page is a preview of Creating React Libraries from Scratch

No discussions yet