A modular

  1. Each file should have its own variable scope, and internal variables between the two modules will not conflict;
  2. Different modules retain the methods of importing and exporting each other, so that modules can communicate with each other. The execution and loading of modules follow a certain mutual relationship to ensure the interdependence between each other.

Two JS modular generated background

  1. In the early days of web development, for the sake of teamwork and code maintenance, many developers would write their JavaScript code in separate files and then load it with a script tag.
  2. Although each code block is in a different file, eventually all JS variables will be in the same global scope, which requires special attention to the problems caused by scoped variable promotion.
  3. If both code blocks declare the same variable and assign a value to it, the end result of the variable name is the end result of the override substitution in load order.
  4. If there is a dependency between two code blocks, we handle the loading order of the modules
  5. I solved this set of problems: we need to put theseScript files are modular.

Three JS modular specification

CommonJS

  • Node.js is an event-driven I/O server-side JAVASCRIPT environment based on the V8 engine.

  • It implements a set of CommonJS modular specifications.

  • In the CommonJS specification, each JS file is a module, and each module can import and export modules using the require function and module.exports icon.

  • What features of modularity do CommonJS include?

The ability to handle module variable scope the ability to import and export modules and the ability to handle basic dependencies ensures module singletons

AMD

  • To meet the needs of Web development, if synchronous loading is also used on the Web side, the page may pause the response while parsing the script file.
  • Therefore, the Web is better suited to the AMD specification (Asynchronous Module Definition).
// index.js
require(['moduleA'.'moduleB'].function(moduleA,moduleB) {
  console.log(moduleB);
})

// moduleA.js
define(function(require) {
  var m = require('moduleB');
  setTimeout(() = >console.log(m),1000)})// moduleB.js
define(function(require) {
  var m = new Date().getTime();
  return m;
})
Copy the code
  • AMD default asynchronous, in the callback function to define the module content, relatively speaking, will be more troublesome to use;
  • AMD modules cannot run directly on node. Require functions can be used with AMD libraries such as require.js loaded in the browser.

UMD

  1. UMD(Universal Module Definition) as a kind ofhomogeneousModular solution, compatible with both AMD and Commonjs syntax.
  2. Isomorphism, that is, we can use the same set of code to run in two different environments, there is no need to maintain multiple sets of code;
  3. UMD outputs the module content by detecting the modularity specification of the current environment, and mounts the module content to the global object if no tree specification is detected.
/* This is an immediate function (this=window or global,factory = moduleContent) */
(function(self, factory) {
  Module.exports interface is an object. If so, it is a CommonJS environment
 if (typeof module= = ='object' && typeof module.exports === 'object') {
    module.exports = factory(); // copy the factory function to module.exports
  /* Determine whether the define interface exposed by the environment is a function, and whether define. Amd exists, if so, it is the AMD specification environment */
 } else if (typeof define === 'function' && define.amd) {
 define(factory) // Call define with the factory function as an argument
 /* If nothing else, hang directly on the global variable umdModule */
 } else {
 self.umdModule = factory(); 
 }
}(this.function() {
 return function() {
 return Math.random(); }}));Copy the code

ESModule specification

  • The CommonJS specification and the AMD specification are:
  1. Modularity specifications defined in the host environment at the top of the language;
  2. Cannot share modules with each other; For example, you can’t use AMD modules directly in NodeJS, and you can’t use CommonJS modules in browsers
  • After ES6, JS has the modularity specification at the language level, that is, ESModule specification, we can import and export modules by import and export two keywords.

  • So the biggest difference with CommonJS and AMD is:

The esModule is implemented by the JS interpreter, while the other two are implemented by the runtime in the host environment. The import of esModule actually adds a new statement at the syntactic level, while AMD and CommonJS load modules actually call the require function.

  • Relationship between the host environment and the JS parser
Node. Js browser (w3c specification) applet global document wx process window swan, write write write _____________________________________ js Core(ecMAScript specification) var a = 123; function test() { console.log(true) }Copy the code
  • Most apis like setTimeout and Console are not implemented at the JSCore level, but all runtime environments implement similar effects
  • SetTimeout entered the JScore level after ES7

Four JS modular outlook

  1. From the current analysis, we can see that modules using ESModule are clearly consistent with the history of JS development

  2. Because any environment that supports JS will eventually support the ESModule standard as the corresponding interpreter is upgraded

  3. However, the Web side is limited by the browser version used by users, we can not arbitrarily use the latest features of JS.

  4. To enable our code to run in users’ older browsers, a growing number of tools have sprung up in the community that statically compile higher-spec code into lower-spec code, most commonly known as Babel.

  5. Babel takes the syntax of the highest specification in JS Core and translates it into the lower specification syntax at a static stage with the same semantics, so that even early browsers, their built-in JS parsers, can understand it.