Js modular specification (commonJs, Es6 modular)

1, Js modularization

Common modular specifications:

1. CommonJS -- nodeJS modular specification

regulations:

  • Each file is a module with its own independent scope, variables, and methods (synchronous loading method), which is invisible to other modules.

  • Inside each module, the module variable represents the current module. This variable is an object, and its exports attribute (i.e. module. Exports) is an external interface. Loading a module actually loads the module.exports attribute of the module. The require method is used to load the module.

characteristic:

  • All code runs within the scope of the module and will not pollute the global scope.

  • The module can be loaded multiple times, but it will only run once when it is loaded for the first time, and then the running results will be cached. When it is loaded later, the cached results will be read directly. In order for the module to run again, the cache must be cleared.

  • Modules are loaded synchronously according to the order in which they appear in the code.

  • Module definition (export):

    Module.exports attribute: loading the module is actually the module.exports attribute of the loading module

    module.exports.add = function () {   //
    ...
    }
    module.exports = function () {		//Anonymous writing
    return ...
    }
    

    **Exports variable: * * node provides an exports variable (can be said to be an object) for each module, pointing to module.exports.

    That is, each module defines:
    	var exports = module.exports;
    When outputting externally, you can use variables export Add method to export on
    
    

    use:

    exports.add = function (r){return Math.PI * r *r};
    

    **Note: * * you cannot directly point exports to a value, which is equivalent to cutting off the relationship between exports and module.exports.

    For example: exports=function(x)	{console.log(x)};
    

    It is recommended to use the module.exports attribute. You can learn about exports

  • Module reference:

    var add = require('./xxx.js');  //Relative path import
    var config = require('xxx.js');  //Direct import
    var http = require('http');		//Import a module
    

    Because nodeJS will be deployed on the server, there is no problem of js module download blocking, but the browser is a local client, which has the problem of js file download blocking.

    Therefore, the browser is not compatible with CommonJS because these Node.js environment variables are missing.

    • module
    • exports
    • require
    • global

    As long as these variables are solved, the following example:

    var module = {
      exports: {}
    };
    (function(module, exports) {
      exports.multiply = function (n) { return n * 1000 };
    }(module, module.exports))
    
    var f = module.exports.multiply;
    f(5) // 5000 
    

    Two external variables, module and exports, are provided to an immediate execution function, and the module is placed in the immediate execution function. The output value of the module is placed in module.exports, which realizes the loading of the module

    Knowing the principle, you can make tools. Browserify It is the most commonly used tool for common JS format conversion.

    You can check teacher Ruan Yifeng's related articles to continue to understand: http://www.ruanyifeng.com/blog/2015/05/commonjs-in-browser.html

    commonJs learn more: http://javascript.ruanyifeng.com/nodejs/module.html

2. ADM -- a modular specification advocated by requireJS

AMD advocates dependency preposition; In requireJS, modules are defined through define. If modules depend on each other, you need to import the dependent modules first. After importing, execute the following code through callback function, so as to effectively solve the problem of module dependence.

Module definition:

define({
	method1: function() {}
	method2: function() {}
});  

//perhaps
define(function(){
	return {
		 method1: function() {},
		 method2: function() {},
	}
});    

Module reference:

require(['a', 'b'], function(a, b){
a.method();
b.method();
})

3,ES6Module

ES6 realizes the module function at the level of language standard, and aims to replace AMD and CommonJs as a common module solution for browsers and servers.

Rule: each js file is a separate module

  • On demand import: the Import command is used to input functions provided by other modules

  • Export on demand: the export command is used to specify the external interface of the module

// Define module math.js 
var data = 0;
var add = function (a, b) { return a + b };

// Export exposed basicNum variable and add method
export { data, add };

//The reference module can omit. js, and the loaded variable name or function name needs to be clear
//as can be renamed
import { data as newName, add } from './math.js';
  • Default import and export
//Specify the default output for the module. You do not need to use braces when import ing. Each module is allowed only once
export default { ... };

import Accepted name (legal requirement) from 'Module path, identifier'
  • Import and execute directly
import '..../xxx.js'

The module of ES6 is not an object. The import command will be statically analyzed by the JavaScript engine. The module code will be introduced during compilation rather than loaded during code running, so conditional loading cannot be realized. Because of this, static analysis is possible.

Keywords: Javascript node.js Front-end

Added by MyWebAlias on Wed, 08 Dec 2021 07:33:14 +0200