The original text is here.
JavaScript doesn’t have import/export modules to begin with. With all the code in one file, it’s a disaster.
Then there were some mechanics that changed and there was only one file. Thus came CJS, AMD, UMD, and ESM. This short article is to give you an idea of what these are.
CJS
CJS stands for CommonJS. It looks like this:
//importing
const doSomething = require('./doSomething.js');
//exporting
module.exports = function doSomething(n) {
// do something
}
Copy the code
CJS is often used in Node development.
- CJS imports modules synchronously
- You can start your
node_modules
Or local directory import modules. Such as:const someModule = require('./some/local/file');
. - CJS imports a copy of the module.
- CJS does not work in a browser. To be used in a browser, transcoding and packaging are required
AMD
AMD stands for asynchronous Module definition. Such as:
define(['dep1'.'dep2'].function (dep1, dep2) {
//Define the module value by returning a value.
return function () {};
});
Copy the code
or
// "simplified CommonJS wrapping" https://requirejs.org/docs/whyamd.html
define(function (require) {
var dep1 = require('dep1'),
dep2 = require('dep2');
return function () {};
});
Copy the code
- AMD introduces modules asynchronously, hence the name
- ADM is for the front end
- AMD is not as intuitive as CJS
UMD
UMD stands for Universal Module Definition. Such as:
(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;
}));
Copy the code
- It can be used on both the front end and back end
- Unlike CJS and AMD, UMD is more like a model for configuring multi-module systems
- UMD is usually the alternate choice for Rollup and Webpack
ESM
ESM stands for ES Modules. Such as:
import React from 'react';
Copy the code
or
import {foo, bar} from './myLib'; .export default function() {
// your Function
};
export const function1(){... };export const function2(){... };Copy the code
- It works in many modern browsers
- You can use both the front and back ends. CJS like simple syntax rules and AMD asynchronyShake the tree
- ESM allows packaging tools such as Rollup and WebPack to remove unnecessary code
- In the HTML call
<script type="module">
import {func1} from 'my-lib';
func1();
</script>
Copy the code
It is not supported by all browsers yet.
conclusion
- ESM, with its simple syntax, asynchrony, and tree-shaking features, is basically the best modular mechanism
- UMD can be used anywhere, so it’s used as a backup packaging solution
- CJS is synchronous and is often used in the back end
- AMD is asynchronous and front-end friendly
Thanks for reading!