First, the importance of modules

Javascript is not a modular programming language. It does not support classes, let alone modules. A lot of effort has been made to implement the “module” effect within the existing runtime environment.

Days without modules

function a() {... };function b() {... };function c() {... };Copy the code

Consequences:

Catastrophe of global variables; Function naming conflicts; Dependencies are difficult to manage.

Js module predecessor (to solve the above problems)

1. Face to face

var obj = {
    a: 1.b: function() {... }};Copy the code

Advantages: 1. Solve the problem of variable pollution; 2, ensure that the module name is unique, to establish the relationship between the members of the same module. Disadvantages: 1, exposed all module members, internal state can be external arbitrary rewriting.

obj.a = 100;Copy the code

2. Anonymous self-executing functions:

(function() {
    var obj = {	
        a: 1,
        b: function() {... }}; }) ();Copy the code

Advantages: 1. Solve the problem of exposing all module members and the internal state can be arbitrarily rewritten externally. Disadvantages: 1, the need to rely on the external to provide in advance.

Second, the commonJS

2009 is a historic year for JS, nodeJS came out of the sky, let JS run on the server side, if JS browser can have no module, but the idea of no module on the server side is absolutely intolerable. The commonJS specification was created by Mozilla engineer Kevin Dangoor in January 2009.

// create module one.js var a ='aaaa';
function b() { console.log(a); }; module.exports = { a: a, b: b }; Var x = require('./one.js');
x.b();Copy the code
Advantages:

1. All code runs in the module scope and does not pollute the global scope; 2, independence is an important feature of the module, it is best not to directly interact with other parts of the program inside the module; 3. The module can be loaded multiple times, but will only run once at the first time of loading, and then run the result is cached. After loading, it will directly read the cached result. For the module to run again, the cache must be cleared; 4. Modules are loaded in the order they appear in the code. Node popularized the commonJS specification, but there were a number of issues in the browser: browser resources were loaded differently than on the server. The server requires a module that reads directly from the hard disk or memory, taking negligible time. Browsers, on the other hand, need to download this file from the server, and then run the code in it to get the API, which takes an HTTP request, which means require a line of code after the resource request completes. Since the browser inserts script tags to load resources (ajax is not a good way to synchronize code execution), writing like CommonJS will result in an error. This means that the specification will have to evolve to accommodate the browser!! A Modules/Wrappings specification appears.

Third, AMD

After some talk, revision (process ignored), the AMD idea emerged… AMD (Asynchronous Module Definition) :

  • The asynchronous module definition specification lays down rules for defining modules so that modules and their dependencies can be loaded asynchronously. This is appropriate for an environment where browsers load modules asynchronously (which can cause performance, availability, debugging, and cross-domain access issues).
  • Dependency preexecution (asynchronous loading: dependencies are executed first, dependencies must be written first, and modules are executed as early as possible. In other words, all require are executed ahead of time (require can be global or local).
  • Related Api(simple example):

    // Define and expose modules
    define("xxx"["xxx"."xxx"].function(x, x) {  
        return. ; });// Load the module
    require(["xxx".".. /xxx"].function(xxx, xxx) {	
        xxxx
    });Copy the code

For details, please refer to: AMD (Chinese version)

RequireJS AMD has to mention the RequireJS IMPLEMENTED by AMD in browsers. RequireJS is a JavaScript file and module loader that follows the AMD specification. Reference file: RequireJS

Third, CMD

CMD (Common Module Definition) :

  • CMD is much closer to CommonJS Modules/1.1 and Node Modules specifications, where a module is a file;
  • It advocates relying on proximity, loading whenever it wants, and implementing lazy loading (delayed execution).
  • There’s no global require, every API is pure and simple;
  • However, RequireJS has been deferred since 2.0.
  • Related Api(simple example):

    // Define and expose module define('xxx'['xxx'].function(xxx, xxx, xxx) {
        return. ; }); // Load module define(function(require, exports) {var a = require(exports)'./a'); // call module A's method a.dosomething (); });Copy the code

seaJS

  • SeaJS follows CMD and implements CMD in the browser;
  • SeaJS is a module loader;
  • It borrows a lot from RequireJS

Seajs website

other

UMD

Since CommonJs is as popular as the AMD style, there seems to be a lack of a unified specification. So there was a need for a “common” pattern that supported both styles, and the Common Module Specification (UMD) was born.

es6 modules

  • ES6 comes with modularity, which is the first time JS supports Module;

Afterword.

This article mainly describes the implementation of module ideas in the browser, not a detailed Api tutorial.