This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging


modular

Modularity andadvantages:

Modularity is the separation of the system into functional modules so that we can load whatever functionality we need.

Advantages of modularity:

  • Avoid namespace conflicts (reduce namespace pollution)
  • Better separation for on-demand loading
  • Improve the reusability of code
  • Improved code maintainability

JS modular development process

CommonJS (server) =>AMD (browser) => CMD => ES6 Module modularity

Type of modularity specification

Trends in modularity specifications

There are three front-end module specifications: CommonJs,AMD and CMD.

CommonJs is used on the server side, AMD and CMD are used in the browser environment

AMD is a normalized output of the RequireJS module definition in the promotion process.

CMD is the normalized output of the SeaJS module definition in the promotion process. \

AMD: Execute ahead (asynchronous loading: dependency first) + delay execution CMD: delay execution (run until required to load, execute according to the order)

CommonJS specification

The concept of CommonJS

Node applications are composed of modules and use CommonJS module specifications.

Each file is an independent module with its own scope. Variables, functions, and classes defined in one file are private and not visible to other files.

  • Each file can be used as a module (by file, I mean JS file)
  • On the server side: Modules are loaded synchronously at runtime
  • On the browse side: modules need to be compiled and packaged in advance, otherwise browsers will not recognize require syntax

The use of CommonJS

It is mainly divided into two steps: defining module and importing module.

Definition module

The CommonJS specification states that within each module, the Module variable represents the current module. This variable is an object whose module.exports property is the external interface. If you load a module, you load the module.exports property of that module.

// Exports the variable 'x' and function 'addX' through 'module.exports'
let x = 1;
let addX = function (value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;
Copy the code

The introduction of the module

The require method is used to load the module.

var example = require('./example.js');
Copy the code

The characteristics of the CommonJS

  • All code runs in the module scope and does not contaminate the global scope.
  • A module can be loaded multiple times, but it is only run once on the first load, and then the result is cached, and later loads read the cached result directly. For the module to run again, the cache must be cleared.
  • Module loading is a blocking operation, i.e., synchronous loading. Modules are loaded in the order in which they appear in the code.

Module loading mechanism

The loading mechanism of the CommonJS module is that the input is a copy of the output value. That is, once a value is printed, changes inside the module cannot affect that value.

AMD specification

ADM concepts

The full name of the AMD specification is Asynchronous Module Definition, which is an Asynchronous Module loading mechanism. It is mainly used in browsers. It completely describes the module definition, dependencies, references, and loading mechanisms. Because the specification is not supported by native JS, developing with the AMD specification requires the introduction of third-party library functions, the AMD counterpart of which is the well-known RequireJS.

  • After the CommonJS specification came along, it worked very well for Node development, and developers wanted to learn from this experience to solve the modularity of browser JS
  • However, most people think that the browser and server environments are too different. After all, the browser’S JS is loaded dynamically over the network, while the server’s JS is stored on local disk. Therefore, the browser needs to realize asynchronous loading, and the module must first know the module it needs to rely on when defining, and then write the module code in the callback function to execute, and finally derived from the AMD specification
  • AMD’s main idea is asynchronous modules, where the main logic is executed in function callbacks.

The use of AMD

The define and require methods that define and call modules are called AMD modes. Its module – defined methods are very clear, do not pollute the global environment, and can clearly show dependencies.

Use define to expose modules and require to import them. Require () loads the module asynchronously so the browser doesn’t become unresponsive; It solves the dependency problem by specifying a callback function that runs only after all previous modules have been loaded successfully.

AMD mode can be used in a browser environment and allows modules to be loaded asynchronously or dynamically as needed.

Define method: Defines a module

The define method is used to define modules, and RequireJS requires each module to be in a separate file. Depending on whether or not you rely on other modules, the discussion can be divided into two cases. The first is to define independent modules, that is, the defined modules do not depend on other modules; The second is to define dependent modules, that is, modules that are defined depend on other modules.

The require method: calls the module

The require method is used to call the module. Its parameters are similar to the define method.

RequireJSTwo problems are mainly solved:

  1. multiplejsFiles may have dependencies, and the dependent file needs to be loaded into the browser before the dependent file
  2. jsThe browser stops rendering the page when it loads, and the more files it loads, the longer the page loses response time

AMD specification compatibility with CommonJS specification

The CommonJS specification loads modules synchronously, that is, only after the load is complete can the following operations be performed. The AMD specification loads modules asynchronously, allowing you to specify callback functions. Since Node.js is mainly used for server programming, the module files are usually already on the local disk, so they can be loaded quickly without the need for asynchronous loading, so the CommonJS specification is suitable. However, in a browser environment, to load modules from the server side, asynchronous mode must be used, so the BROWSER side generally uses the AMD specification.

CMD specification

The concept of CMD

CMD(Common Module Definition), it solves the same problem as the AMD specification, but in the Module Definition and Module loading time is different, CMD also needs to introduce additional third-party library files,SeaJS,SeaJS recommended a Module a file

  • The AMD/RequireJS JS module implementation has many inelegant features, mainly because it cannot be loaded and executed in a way that better manages module dependencies;
  • SeaJS follows the CMD specification. The CMD specification is improved on the basis of AMD, which solves the problem of execution time of AMD dependent modules.
  • The order of SeaJS modularization is: Modularization preloading = “the code in the module is executed when the main logic calls the module;
  • The usage of SeaJS is basically the same as that of AMD, and combines CommonJS writing methods.

The use of CMD

(For the introduction of modules, there are both synchronous and asynchronous modes)

Define is a global function that defines modules

SeaJS provides seajs.use to load modules

SeaJS emerged as a CommonJS practitioner in browsers and absorbed the benefits of RequireJS

UMD (AMD + CommonJS)

CommonJS is applicable to the server, AMD, CMD is applicable to the Web, so the need to run at both ends of the module can be used UMD method, using the modular scheme, can be well compatible with AMD, CommonJS syntax. UMD first checks if there are modules (exports) that support Node.js, and if there are, uses node.js module mode. Then check whether AMD is supported (whether define exists). If yes, the module is loaded in AMD mode. Because of the applicability of this generic module solution, many JS frameworks and class libraries are packaged in this form of code.

Module in ES6

Only static import and export is supported

The ES6 specification only supports static imports and exports. ES Modules require static Module optimization at compile time, which means that it must be determined at compile time.

There are two main reasons why we should do this:

  1. Performance: all modules are imported at compile time, which will slow down if done at run time
  2. Better check for errors, such as variable types

ES6 Module using

  • The module function consists of two commands:exportandimport
  • exportUsed to expose interfaces,importFor importing modules

It is worth noting when using the ES Module: The import and export commands can only be executed at the top level of the Module and will report errors in the code block. This is because ES Module requires static Module optimization at compile time. Import and export commands are statically analyzed by the JavaScript engine and executed before other statements in the Module. This design makes the compiler more efficient, but it also makes it impossible to load modules at run time (dynamic loading).

In response to this shortcoming, TC39 has a new proposal — Dynamic Import. The content of the proposal is to introduce the Import () method to implement Dynamic module loading.

// specifier: specifies the location of the module to be loaded
import(specifier)
Copy the code
  • The import() function can be used anywhere, not just in modules, but also in non-module scripts.

It is run time execution, that is, when this sentence is run, it is loaded into the specified module. Also, unlike import syntax, the import() function loads modules that are not statically linked

  • Note that ES6’s Module syntax is not supported by some browsers, so you need to Babel advanced transcoding to convert import and export commands into ES5 syntax before the browser can parse them.

CommonJS, AMD, CMD, and ES6 Modules

AMD is different from CMD

  1. Dependencies are handled differently when modules are defined

    AMD advocates pre-dependent modules, which are declared when modules are defined. CMD pushes dependencies from the nearest module and uses require import only when a module is needed.

  2. Dependent modules are handled differently

    First of all, AMD and CMD load modules asynchronously, but the difference is that AMD executes the dependent modules immediately after loading them, and the execution order of the dependent modules may not be the same as the order in which we write them. When CMD loads a dependent module, it does not execute the module immediately. When all the modules are loaded, it enters the return function logic and executes the corresponding module when it meets the require statement. In this way, the module execution order is the same as when we wrote it

ES6 module and CommonJS module loading difference

CommonJS is loaded at runtime, because ComminJS loads the entire module, generates an object (which contains all the API of the path module), and then reads the method from that object —– ES6 is loaded at runtime, ES6 is not an object, Its external interface is just a static definition, which generates —– at compile time when the code is static

/ / ES6 module
import { basename, dirname, parse } from 'path';

/ / CommonJS module
let { basename, dirname, parse } = require('path');
Copy the code

How is this different from CommonJS module loading?

  • When require path, CommonJS runs the path module once and returns an object containing all of the PATH module’s apis.

conclusion

Modularity is the separation of the system into functional modules so that we can load whatever functionality we need.

Advantages of modularity:

  • Avoid namespace conflicts (reduce namespace pollution)
  • Better separation for on-demand loading
  • Improve the reusability of code
  • Improved code maintainability

CommonJS (server) =>AMD (browser) => CMD => ES6 Module modularity

CommonJs is mainly used on the server side, AMD and CMD in the browser environment. AMD is a normalized output of the RequireJS module definition in the promotion process. CMD is the normalized output of the SeaJS module definition in the promotion process. The ES6 specification only supports static imports and exports. Unlike CommonJS runtime loading, which is compile-time loading for ES6, ES Module is statically optimized at compile time.


If this article helped you, remember to like 👍 collection and follow oh 😊, hope to like a lot more…

If there are any mistakes in this post, feel free to correct them in the comments section