The loving mother hand line, wandering clothes. Although this is an unfortunate metaphor, much of the knowledge in my mind is as tangled as a ball of wool in my hand, and requires a net to weave it into shape, as so has documented in this article.

Sparrow, the original language (the original article format looking at more comfortable) : www.yuque.com/docs/share/… CJS/AMD/CMD/UMD/ESM

This article will briefly talk from the following points:

  • Antecedents feed
  • CommonJs / CJS
    • concept
    • The characteristics of
    • NodeJs modularity
  • AMD (Asynchronous Module Definition)
    • concept
    • The characteristics of
    • Require.js module loading principle
      • Simple to use
      • The principle is introduced
  • CMD (Common Modules Definition)
    • The characteristics of
  • UMD (Universal Module Definition)
    • The principle of
  • ES Module
    • The characteristics of
    • ES6 import & Export
  • Q&A module loading at run time and loading at compile time
  • other

Antecedents feed

Code modularization has long been a basic operation (basic operation), it is well known that there are CommonJs, AMD, CMD, UMD, ES Module these five kinds of solution specification, the article is the record of their own learning, if there is a mistake welcome everyone to criticize.

CommonJs / CJS

CommonJs is a specification.

concept

I’ve condensed a few of the highlights mentioned in Wikipedia (commonjs-wiki-link) into the following: ** For the environment: ** JavaScript projects outside of web browsers (non-Web browser environments) Project objectives: Modular solutions for JavaScript ecology ** Main Examples: ** Especially using nodeJs for server-side JavaScript programming ** Browsers: ** Browsers cannot execute CommonJs code directly, need to be converted by compilation ** How to identify: CommonJs is not an ES module published by the ECMA organization, but many ECMA members participate in it.

The characteristics of

  1. All code runs in module scope and does not pollute global variables;
  2. Modules are loaded synchronously according to the order in the code;
  3. The module will be loaded and executed at run time, resulting in object A, and any subsequent require is A copy of the value of object A (in other words, the module can be loaded multiple times, executing and caching its results on the first load and returning the results directly on subsequent loads). The cache must be cleared before the module can run again.

If you want to execute a module multiple times, you can export a function and then call the function.

NodeJs modularity

  1. Before executing the module code, NodeJs wraps it with the following function wrapper;
  • Variable pollution is avoided in the form of closures.
  • Provides module-specific variables that look global;
(function(exports.require.module, __filename, __dirname) {
	// The module code is actually here
})
Copy the code
  1. Module contents can be exported through module.exports;
  2. Exports is a reference to module.exports, so no assignment can be made to exports;
  • exports = module.exports;
  • The exports variable is available in the module’s file-level scope and is assigned to before the module executesmodule.exports;
  • somodule.exports.f = ...I can write it more succinctlyexports.f = ...;
// exports is reassigned, this function was not exported
exports = function(x) {console.log(x)}; 

// Correct usage
exports.a = function (x){ console.log(x); };/* module.exports was overwritten and exports was overwritten. This means that if a module's interface is a single value, it is better not to use exports, but to use module.exports. * /

exports.hello = function() {
  return 'hello';
};

module.exports = 'Hello world';

Copy the code
  1. Import modules, JSON, or local files via require(ID);

  2. The module introduced by require.cache will be cached in this object. Deleting a module from this object will cause the module to be reloaded the next time require is performed.

AMD (Asynchronous Module Definition)

Asynchronous modular definition of JavaScript.

concept

** For the environment: ** Web Browser Project Objective: Modular solution for JavaScript ecology ** Main Example: **require.js ** How to identify: ** We can use define(ID? , dependencies? , factory); Function to identify whether the AMD specification is used.

// exports, "require", "exports", "beta
define("alpha"["require"."exports"."beta"].function (require.exports, beta) {
  exports.verb = function() {
    return beta.verb();
    //Or:
    return require("beta").verb(); }});Copy the code

The characteristics of

  1. All code runs in module scope and does not pollute global variables;
  2. Modules are loaded asynchronously;
  3. Once the dependent module is loaded, its callback function (factory function) is executed immediately.
  4. The main module will wait until all dependent modules are loaded, and then call its corresponding callback function (dependency front).

Require.js module loading principle

Simple to use

First, a brief introduction to the use of require.js:

  1. Within the HTML file, you need onescriptTags introducedrequire.jsAnd the entry file for the projectmain.js;
  2. The main logic of the project is in the main.js file.

The project structure is as follows: project-directory/

  • project.html
  • scripts/
    • main.js
    • helper/
      • util.js
<! -- project.html -->

<! DOCTYPEhtml>
<html>
    <head>
        <title>My Sample Project</title>
        <script data-main="scripts/main" src="scripts/require.js"></script>
    </head>
    <body>
        <h1>My Sample Project</h1>
    </body>
</html>
Copy the code
// main.js

requirejs(["helper/util"].function(util) {
    // you can do everything you want
});
Copy the code

The principle is introduced

As of 2.0, however, RequireJS has been changed to defer execution.

Objective:

  • Understand require using the script tag
  • Check whether the script tag loaded successfullyonloadThe implementation details are not discussed
  1. When we introduce require.js, we’ll passdata-mainImport import file;
  2. Require. js gets the entry file and passes the file and its corresponding dependenciesscriptTag append to HTML;
  3. Dependencies are sequentially and synchronously appended to HTML, but script tags are loaded asynchronously;
  4. After a dependency is loaded, its callback execution function is called immediately.
  5. The import file listens until all dependencies are loaded and then calls its callback (factory).

CMD (Common Modules Definition)

CMD is the standardized output of module definition in the promotion process of Sea-.js. Much like AMD, the similarities and differences are briefly discussed here.

The characteristics of

  1. All code runs in module scope and does not pollute global variables;
  2. Modules are loaded asynchronously;
  3. After a module is loaded, it does not execute its callback function, but does not run its dependency function until the main function runs and the dependency needs to be executed (dependency post, load on demand).

UMD (Universal Module Definition)

UMD provides a “generic” schema that supports multiple styles and is compatible with CommonJS and AMD specifications while also being compatible with global references.

(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

The principle of

The implementation principle is simple.

  1. Check whether AMD is supported. If yes, load the module in AMD mode. Otherwise, go to Step 2.
  2. Check whether CommonJs is supported. If yes, use the node. js module format. Otherwise, go to Step 3.
  3. Expose modules globally (Window or Global)

ES Module

ES Module is the ECMAScript standard for handling modules. Modern browsers (older versions) basically support ES Module.

<script type="module" src="index.js"></script>
Copy the code

The characteristics of

  1. All code runs in module scope and does not pollute global variables;
  2. Output modules at compile time;
  3. The output module content is read-only and cannot be modified.
  4. Module results are not cached, and module contents are dynamically executed each time;

ES6 import & Export

ES6 is gay. It has to be. This article is very well written. The difference between require and import – links

  1. Import statements will be promoted;
  2. Import variables are read-only;
  3. Import is executed statically, so expressions cannot be used;
  4. Import statements support the Singleton pattern (if the same import statement is repeated multiple times, it is executed once, not multiple times). ;
  5. Export requires the output of an object or variable declaration statement;
  6. Export default outputs a variable/object named default.
  7. Export and import;
    1. Foo and bar are not actually imported into the current file, rather they are forwarded through the entry file, which is usually used as a relay to utils/index.js. Other places can pass**import {foo} from 'util'**Reference the file
export { foo, bar } from 'my_module';

// It can be used as an example
import { foo, bar } from 'my_module';
export { foo, bar };
Copy the code

Q&A module loading at run time and loading at compile time

In traditional compiled languages, a piece of source code in a program goes through three steps, collectively known as compilation, before execution. Word Segmentation/Lexical Analysis -> Parsing/Parsing -> Code Generation. The import statement in ES6, which is generated during compilation, introduces the address of the module, so it will dynamically get the address to execute the corresponding content during execution. RequireJs requires (‘foo’) a module, which is a “dead” copy of the module’s value. If you need to run it again, you need to manually clean the require.cache module.

The end of the

This is the end of the article, the content is mainly “theory”, I will output what I know into the form of videos and articles, test my foundation and hope to “solve the doubts” for confused friends. Thanks for watching and see you next time!

Other recommended

Refer to a list of articles:

  1. www.jianshu.com/p/eb5948a70… The evolution of JavaScript modularization (Commonjs, AMD, CMD, ES6 modules)
  2. www.jianshu.com/p/d7fdcc89f… CommonJS, AMD, CMD, ES6 Module
  3. www.jianshu.com/p/929b56dcf… Modular development
  4. Segmentfault.com/a/119000002… The difference between require and import
  5. Juejin. Cn/post / 684490… Modular AMD and CMD principles
  6. Dev. To/iggredible /… What are CJS, AMD, UMD, and ESM in Javascript?