Modular js-

1. What is modular:

A complex process based on certain rules (specification) packaged into several blocks (files), and combined with internal data block / private implementation is only exposed some interfaces (methods) other communication with an external module to the outside .

development process:

(1) non-modular (originally written all the js code in a file, so that is not conducive to reading to find)

the introduction of script tag file, list each other, but are dependent on the front, otherwise it will error.

<script src="jquery.js"></script>
<script src="jquery_scroller.js"></script>
<script src="main.js"></script>
<script src="other1.js"></script>
<script src="other2.js"></script>
<script src="other3.js"></script>

That is simply all js files all together, but the order of these files also can not go wrong, such as the need to introduce jquery, jquery plugin in order to introduce in order to use jquery in other documents.

Disadvantages:

  • Pollution global scope (global)
  • It is easy to naming conflicts
  • High maintenance costs
  • Dependency is not obvious
  • Coupled with high (strong association is not conducive to post-maintenance) (What is the coupling 'high coupling, indeed affect the whole body':? 'Low coupling, a relatively low correlation')

(2) Simple encapsulation: Namespace mode (. The data on the part of the object, through the operation object attribute data)

     Features: Reduce the number of variables on the global, but the essence is the object, not safe.

(3) closure Anonymous: IIFE mode (some logic functions written in immediate execution), so relatively safe.

(4) introducing dependent

2. Why should Modular

(1) to reduce complexity, reduce the coupling, reducing the complexity between them.

(2) ease of deployment (such as special modules js1 FIG facing the rotation, but the area does not rotate FIG, this area is no need to introduce entirely).

3. The benefits of modularity

(1) avoid naming conflicts (to reduce pollution namespace)

(2) better separation, demand loading

(3) higher reusability

(4) High maintainability (easy maintenance)

4. page introduction to load script

But the reality is:

To load multiple script tags, to initiate multiple requests, rely on vague, difficult to maintain.

5. Specification

CommonJS (node ​​according to the preparation of the specification)

specification:

(1) Each file can be used as a module

(2) at the server side: the loading module is synchronized (waits blocking) runtime loading

(3) in the browser: module compiler package deal in advance

grammar:

  Injection module: require (xxx)

    Third-party modules: xxx is the module name

    Custom module: xxx is the module file path

  Exposure module:

    (1) module.exports = value (exoports itself is an empty object, module.exports = value is added to a property or method exports an object.)

    (2) exports.xxx = value (exports.xxx = value is directly covered by the value of the original object to the new object is empty.)

        module.exports={foo:'bar'};//true

        module.exports.foo='bar';//true

        export = {foo: 'bar'}; // false, corresponding to a re dependent on exports

    Question: module is exposed nature exports target

advantage:

  • Resolve dependencies, global variable pollution problems

Disadvantages:

  • CommonJS loading module in a synchronous manner. In the service side, there is a local disk module file, reads very fast, so this is no problem. But the browser is limited to network reasons, CommonJS not suitable for browser-side module is loaded , a more reasonable solution is to use asynchronous loading, such as below AMD specification.

The AMD (dedicated browser for a modular specification, the load module is asynchronous to achieve (browser): Require.js)

 grammar:

  Definition of exposure modules:

    // definition does not depend on the module:

    define(function(){

      return module

    })

    // definition has dependent modules:

    define(['module1','module2'],function(m1,m2){

      return module

    })

Different from CommonJS, AMD specification 被依赖 module is loaded asynchronously, and the module is defined as a callback function to perform, depending on require.js module management tool library. Of course, AMD is not using standardized 匿名函数自调用 way to package, we can still achieve private members and public members of the module using the principle of closure:
define(['module1', 'module2'], function(m1, m2) {
    let x = 1;
    function add() {
        x += 1;
        return x;
    }
    return { add };
})

 

  The introduction of the use of modules:

    require(['module1','module2'],function(m1,m2){

      Use m1 / m2

    })

CMD (specifically for browser-side load module is asynchronous, when the load module will perform, implement (browser): Sea.js )

AMD respected depend front, CMD respected rely nearby.

CMD integrates features CommonJS and AMD, supports synchronous and asynchronous load modules. CMD is not executed after a complete load dependent module, just download it, it executes the corresponding module when all the dependent modules loaded into the main logic encountered require statement, so the module execution order and written order is exactly the same of. Thus, in the CMD require no HTTP request procedure when a function module loaded synchronously.

 The basic syntax:

  // definition does not depend on the module:

  define(function(require,exports,module){

    exports.xxx = value

    module.exports = value

  })

  // definition has dependent modules:

  define(function(require,exports,module){

    // introducing dependent module (sync)

    var module2 = require("./module2")

    // introducing dependent module (asynchronous)

    require.async("./module3",function(m3){

    })

    // exposure module

    exports.xxx = value

  })

  The introduction of the use of modules:

   require(function(require){

    var m1 = require('./module1')

    var m4 = require('./module4')

    m1.show()

    m4.show()

  })

ES6

Description: the compiler packing process module requires dependence;

Features:

  • Modular output is a copy of a specification value, ES6 module output is a reference value.
  • Modular runtime specification is loaded, ES6 is an output interface module at compile time.

grammar:

  (1) Export module: export xxx

  (2) introduction module: import xxx from "url"

Realization (browser):

  (1) Use ES6 Babel will be compiled into ES5 (Some browsers are not compatible ES6)

  (2) use Browserify compiler package js


 

ES6 Modular details:

1. First page references need to add type = 'module' in the <script> </ script> in

2. Export module is divided into default export and specify export

        name = the let 'wangwu' ; 
        the let Age = 18 ; 
        the let module1 = function () { 
            console.log ( `Hello, I'm $ (name), this year $ (age) years old .`) 
        }; 
        Export default module1; // default export 
        export {name, Age, modue1} // specify export

 

 The main difference between the two is that when references:

  • If the default is derived export default, when the received may be used to receive any name , as shown below, called Module1 derived, received name x:
import x from 'js/module1.js';

 

  • If you want to export a plurality, need wrapped {}, the time of reception must be the same name and export:
import {name,age,module1} from 'js/module1.js';

 

  • If a module has both default export, but also export specified
Export default Module1; // default export 
Export {name, Age, Module1}; // Specify Export

 

    Upon receipt may be used:

X Import, {name, Age, Module1} from 'JS / module1.js'; // default derived still can be named

 

3. If it is the same directory, you must add ./

If there are two modules in export content is the same, this time console.log, will error

X Import, {name, Age, module1} from './module1.js' ; 
Import Y, {name, Age, module1} from './module2.js' ; 
the console.log (name); // this case module1 , module2 are derived name error
X Import, AS NAME1 {name} from './module1.js'; 
Import Y, AS NAME2 {name} from './module2.js' ;
 // AS corresponding to rename 
the console.log (NAME1); 
Console. log (name2);

 4. Only import will only execute code that does not perform the function

  There is a new module.js:

the console.log ( 'which is module3' );
 function X () { 
  the console.log ( 'inside which is a function of module3' ); 
}

 

   And then directly quoted in main.js inside:

Impotr './module3.js';

 

   You can only see print 'This is module3', and the function is not executed.

The collective import

  If the module in the export of many things, do not want to quote the time to write out one by one, it can be:

AS * from X Import './module1.js'; // here understood as the css * wildcard, which means that all

 

   At this time, print out x, you can see

 module1.js which are exported at x, and now can be called with x.age (), x.module1 ().


 

ES6-Babel-Browserify Tutorial

1. Define package.json file

{
  "name":"es6-babel-browserify",
  "version":"1.0.0"   
}

 

2.安装babel-cli,babel-preset-es2015和browserify(cli:command line interface)

* Npm install babel-cli browserify -g (babel global installed)

* npm install babel-preset-es2015 --save-dev 

* Preset default (the es6 convert all plug into es5 package)

3. Define . Babel rc file (rc: control file run control operation, is running to read the file)

{
  "presets":["es2015"]  
}
...

 

 4. encoding

* Js / src / module1.js were exposed

 

 

 

 Original references: https://www.jianshu.com/p/ae4e566212ff

 Original references: https://www.imooc.com/article/43781?block_id=tuijian_wz

 Original references: https://www.jianshu.com/p/2be0e7956854

Guess you like

Origin www.cnblogs.com/czh64/p/11950819.html