Functions and reasons of modularization:

  • The main reason is that real code can be reused, have independent scope, prevent global pollution, improve development efficiency, reduce maintenance cost and so on.
  • Once we have modules, we can load corresponding modules according to the corresponding requirements. We can load whatever functions we want. NPM is the largest repository of modules.
  • However, in the early days, multiple specifications emerged from the JS modularity specification.
  • Fortunately, the trend now and in the future will be for the ESM specifications natively supported in ES6 to prevail.

JS modular specification classification (up to the following 5) : CJS, AMD, CMD, UMD, ESM.

CJS specification

  • The specification stands for library: CommonJS

Common.js is mainly used at the back end. In NodeJS, node applications are composed of modules, using the CommonJS module specification. Each file is a module, with its own independent scope, variables, methods, etc., invisible to other modules. Modules can be loaded multiple times, but only run once on the first load, and then the results are cached and read directly from the cache when they are loaded later. For the module to run again, the cache must be cleared. The order in which modules are loaded, in the order they appear in the code.

CommonJs website

Example code:

    // Define the module math.js
    var basicNum = 0;
    function add(a, b) {
      return a + b;
    }
    module.exports = { // Write functions and variables that need to be exposed here
      add: add,
      basicNum: basicNum
    }
    
    /** the./ path must be added, otherwise only **/ will be found in node_modules
    // When referencing a custom module, the argument contains the path and can omit.js
    var math = require('./math');
    math.add(2.5);
    
    // No path is required when referencing core modules
    var http = require('http'); http.createService(...) .listen(3000);
Copy the code

Two, AMD specification:

  • The specification represents the library: require.js

RequireJS is a JavaScript module loader (file and module loading tool). Using RequireJS to load modular scripts improves code loading speed and quality. It is optimized for browser usage and can be used in other JavaScript environments. Examples are Rhino and Node.js.

RequireJS official website, require.js download

Example code:

    /** 网页中引入require.js及main.js **/
    <script src="js/require.js" data-main="js/main"></script>
    
    /** main.js entry file/main module **/
    // First specify the module path and reference name with config()
    require.config({
      baseUrl: "js/lib".paths: {
        "jquery": "jquery.min".// The actual path is js/lib/jquery.min.js
        "underscore": "underscore.min",}});// Perform basic operations
    require(["jquery"."underscore"].function($, _){
      // some code here
    });
Copy the code

Iii. CMD specification:

  • Specification representative library: sea-.js

SeaJS is a JavaScript module loading framework that implements the modular development and loading mechanism of JavaScript. CMD is very similar to AMD, except that AMD relies on front-loading and up-front execution, while CMD relies on nearby and delayed execution. This specification was actually created during the promotion of Sea-js.

SeaJs official website, sea.js download

Example code:

    define(function(require, exports, module) {
        var a = require('./a'); // If required
        a.doSomething();
        if (false) {
            var b = require('./b'); b.doSomething(); }});/** sea.js **/
    // Define the module math.js
    define(function(require, exports, module) {
        var$=require('jquery.js');
        var add = function(a,b){
            return a+b;
        }
        exports.add = add;
    });
    
    // Load the module
    seajs.use(['math.js'].function(math){
        var sum = math.add(1+2);
    });
Copy the code

Iv. UMD Specification:

  • UMD specification is only a general writing method, is in amd and CJS two popular and not unified specification situation, only spawned UMD to unify the specification, UMD can be used before and after.

Example code:

    (function (root, factory) {
        if (typeof define === 'function' && define.amd) {
            // AMD
            define(['jquery'.'underscore'], factory);
        } else if (typeof exports === 'object') {
            // Node, CommonJS, etc
            module.exports = factory(require('jquery'), require('underscore'));
        } else {
            // Browser global variables (root = window)
            root.returnExports = factory(root.jQuery, root._);
        }
    }(this.function ($, _) {
        / / property
        var PI = Math.PI;
        
        / / method
        function a() {};// Private method because it is not returned
        function b() { return a() };        // Public method because it is returned
        function c(x, y) { return x + y };  // Public method because it is returned
    
        // Expose public methods
        return {
            ip: PI,
            b: b,
            c: c
        }
    }));
Copy the code

5. ESM Specification:

  • The ESM specification is native to ES6, and many browsers are starting to support it. The commonJs-like writing and synchronous and asynchronous loading mechanism can be set to HTML by setting type=module, and node is also starting to support it.

Export Export default XXX;

Import import {xx, xx} from ‘./xxx.js’;

Example code:

    /** Define the module math.js **/
    var basicNum = 0;
    var add = function (a, b) {
        return a + b;
    };
    export { basicNum, add };
    
    /** references the module **/
    import { basicNum, add } from './math';
    function test(ele) {
        ele.textContent = add(99 + basicNum);
    }
Copy the code

No matter how many modularity specifications there are, just understand how to define (export) modules and how to use (reference) modules!! arunachal