A Brief Guide to JavaScript Modules and What They Do
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:
// add.js
function add(a, b) {
return a + b;
}
module.exports = add;
Importing code uses the require()
syntax. To use add()
in a separate file we use require()
to point to the add.js
file.
// anotherFile.js
const add = require("./add");
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(["react", "react-dom"], function(react, reactDOM) {
reactDOM.render( , );
});
This page is a preview of Creating React Libraries from Scratch