Front end modular background

Js is designed for page animation + form submission without the concept of modularity + namespace.

Js modular evolution process

  1. Global function

    Encapsulate different functions into different functions

    Disadvantages: Easy to cause global naming conflicts

function m1() {}
funciton m2() {}
Copy the code

2. The simple object approach

  • Reduce global variables and resolve naming conflicts

    Disadvantages: Data insecurity, external can directly modify the data of internal modules

  let myModule ={
    data:'test 123'.foo() {
      console.log(this.data);
    }
  }
  myModule.data = '123'
  myModule.foo(); // External call 123
Copy the code

3. IIFE mode

  • Data is private and can only be used externally by exposed methods

       let getName = (function(dep1,dep2){
          let data = 'Test data';
          let obj = {
            data,
          }
          function test1 () {
            data = 'ffff'
            obj.data = 'Object changes'
            console.log(data+'1');
          }
    
          return {
            test1,
            data,
            obj
          }
        })('name'.'age');
    
        getName.test1(); // ffff1, only dynamic operation data return
        console.log(getName) // {data: test data,obj:{data: change of object}}
       // Simple value, will not change; The reference to the object changes
        
    Copy the code

Uncover patterns: The upper layer does not need to understand the underlying implementation, only the abstraction

  • Continue modular expansion
  • The steering framework: juery | vue | react
  • Design patterns

4. Script tag is introduced

  • Request too much
  • Relying on the fuzzy
  • Difficult to maintain

Question: What is the difference between normal async and defer?

Conclusion:

  • Normal: Parsing blocks immediately, execution of the current script blocks immediately, rendering blocks, and then the next script

  • Defer: parse until the asynchronous load starts, then execute after parsing and Defer in sequence; Suitable scenario: main path first (download resources first, let users see the page first, in the execution of logic)

  • Async: : parsing starts asynchronous loading, executes after downloading and blocks rendering, and continues rendering after execution. Async has no order. Modular experience is preferred (download resources first, repeat execution will result in page redrawing, perform drawing last is better)

What is modularity

  • Encapsulate a complex program into several blocks or files according to certain rules and combine them together
  • The internal data of the block is private, exposing only some interfaces to communicate with the outside world

Benefits of modularity

  • Avoid naming conflicts
  • Better separation of code, load on demand
  • Higher reuse
  • Higher maintainability

Modular specification

commonjs

Nodejs modular specification, implemented first on the server side. CJS, for short, can also be used in a browser environment

1. The concept

  • Any file is a module;
  • Variables, functions, and classes defined in one file are private and invisible to other files.
  • Only export interfaces to interact with other modules

2. Basic grammar

     module.exports = value;  / / export
     exports.xxx = value
     const a = require('sdfsdf')  / / introduction
Copy the code

3. The CJS characteristics

  • Modules can be loaded multiple times, but only run once on the first load; The results are cached
  • Order to load
  • Module loading mechanism, once a value is output, internal changes do not affect the value
    var counter = 3;
      var obj ={
        counter:1
      }

      function incCounter () {
        counter++;
        obj.counter = 2;
      }

      module.exports = {
        counter,
        obj,
        incCounter
      }

      const {  counter,obj,incCounter} = require('./testnode.js');
      console.log('incCounter',incCounter())
      console.log('counter',counter); // 3, there is cache
      console.log('obj',obj); // Object reference obj:{count:2}
Copy the code

4. Why is CJS designed to be synchronous

  • Node module files usually already exist on the local disk, so they can be loaded quickly and there is no need to use asynchronous mode

AMD specification

1. The concept

An asynchronous loading module + callback function idea, mainly on behalf of the library is require.js. CJS is loaded synchronously, and in a browser environment it is expected to be loaded asynchronously

2. Grammar

  • Define defines code as a block;
  • Through the require method, the implementation of code module loading.
   define('name',[dep,dep2],(dep1,dep2) = > {
     / / logic
     return {  // Expose the interface}})Copy the code

CMD specification

1. Concepts are dedicated to the browser side, and module loads are asynchronous. Represents a combination of sea. Js AMD & CJS

2. Grammar

  define('module',[deps],function(require.exports.module){})Copy the code

ES6 specification

1. Official implementation of concept JS modularization

2. Grammar

     import a form  'module';

     export const a = 'sfs'; // You must know the name of the loaded variable or function, otherwise it cannot be loaded

     export default {} // The default export allows users to load modules without reading the document
Copy the code

3. Reference of characteristic value, dynamic reference, no cache value, module variable bound to its module

      export let counter = 3;
      export function incCounter() {
        counter++;
      }

      import {counter,incCounter} from './lib';

      console.log(counter) / / 3
      incCounter();
      console.log(counter) // 4 No cache, value reference
Copy the code

CJS && ES6 Module

  • The difference between

    The CJS module output is a copy of the value, and ES6 is a reference to the value of the output

  • CJS is loaded at runtime and ES6 is the compile-time output interface

    CJS exports an object that is fully generated when the script runs, whereas ES6 is a static definition that is generated during code static parsing

  • When CJS is running, load the whole module and read the interface when it is used. Es6 can specify a value to load, rather than the entire module.

An additional problem

Why do some open source frameworks take global, pointer, and frame references as parameters

(function(window, $,undefined){

      Window.webshow = function(){}}) (window, jQuery)Copy the code

// Block the thread

Windon’s global scope is converted to local scope to improve execution efficiency 2. Compile time optimization

Jquery 1. Separate customization and mount 2. Prevent global crosstalk

Undefined prevents overwriting

If compatible with old code in AMD

Define (' amdMOdule, [],require= >{})Copy the code

Handwriting compatible with CJS&AMD

Copy the code

How do CJS and ES Modules support each other

  • CJS supports ES Modules

1. Before the Node version does not support, use some build tools (webpack), pack js files, Node environment, into the packaged file on the line

   // webpack packs filesIntroduced/dist/main. Jsimport main from './dist/main.js';
Copy the code

2. Node officially supports the file name extension of.mjs

The main, MJS fileimport a from './main.js';
   function c() {}export defalut c;
Copy the code
  • Es Module supports CJS

The ESM can load CJS directly, only as a whole. Because THE ESM is a static parser, the CJS export is an object that can only be loaded together.

  
Copy the code