In the beginning, Javascript did not have a way to import/export modules. This is a problem. Imagine writing your app in just one file - it would be nightmarish!
Then, people much, much smarter than me attempted to add modularity to Javascript. Some of them are CJS, AMD, UMD, and ESM. You may have heard some of them (there are other methods, but these are the big players).
I will cover high-level information: syntax, purpose, and basic behaviors. My goal is to help readers recognize when they see them in the wild 💡.
CJS is short for CommonJS. Here is what it looks like:
//importing
const doSomething = require('./doSomething.js');
//exporting
module.exports = function doSomething(n) {
// do something
}
node_modules
or local dir. Either by const myLocalModule = require('./some/local/file.js')
or var React = require('react');
works.AMD stands for Asynchronous Module Definition. Here is a sample code:
define(['dep1', 'dep2'], function (dep1, dep2) {
//Define the module value by returning a value.
return function () {};
});
or
// "simplified CommonJS wrapping" https://requirejs.org/docs/whyamd.html
define(function (require) {
var dep1 = require('dep1'),
dep2 = require('dep2');
return function () {};
});
UMD stands for Universal Module Definition. Here is what it may look like (source):
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["jquery", "underscore"], factory);
} else if (typeof exports === "object") {
module.exports = factory(require("jquery"), require("underscore"));
} else {
root.Requester = factory(root.$, root._);
}
}(this, function ($, _) {
// this is where I defined my module implementation
var Requester = { // ... };
return Requester;
}));
ESM stands for ES Modules. It is Javascript's proposal to implement a standard module system. I am sure many of you have seen this:
import React from 'react';
Other sightings in the wild:
import {foo, bar} from './myLib';
...
export default function() {
// your Function
};
export const function1() {...};
export const function2() {...};
<script type="module">
import {func1} from 'my-lib';
func1();
</script>
This may not work 100% in all browsers yet (source).
Thanks for reading, devs! In the future, I plan to write in depth about each module, especially ESM because it is packed with many awesomeness. Stay tuned!
Let me know if you notice any errors.