Modularity is mainly used to isolate common code, isolate scope, avoid variable conflicts, etc. Decompose a complex system into modules for easy coding.

The following will be covered

  1. CommonJS
  2. AMD and core principles
  3. CMD and core principles
  4. UMD and source code analysis
  5. ES6 Module
  6. Webpack packaging strategy

CommonJS

Synchronous loading

The CommonJS API is a project with the goal of building a JS ecosystem outside of the browser environment

If there is no Node suffix, the system tries to add. Js,. Json, and. Node to the file name.

.js files are parsed as text JavaScript script files,.json files are parsed as json text files, and.node files are parsed as compiled binary files.

AMD

Load (objects) asynchronously

The “Asynchronous Module Definition” is proposed by RequireJS

AMD Core Implementation

  functionRequire (url, callback) {// the url can be changed to List, and then iterate; var$script = document.createElement('script');
    $script.src = url; // Use the onload callback to implement dependency loading$script.onload = function(e) {// omit callback callback(); } document.body.appendChild($script);
  }

Copy the code

CMD

According to the need to load

Seajs (seaJS), parsing and loading modules on demand (expensive), requires parsing modules into strings to know which modules depend on

CMD core implementation

// Ajax, in case you forget how to write native Ajax. Let me write one downfunction myAjax (url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url);
    xhr.send();

    xhr.onreadystatechange = function () {
      if (request.readyState === 4) {
          if (request.status === 200) {
              return callback(request.responseText);
          } else {
              // 省略...
          }
      } else{// omit... }}} // implementationfunction require(url) {
    myAjax(url, function(res) {// The String form of the JS corresponding to res // parsing is omitted // executioneval(res);
    });
  }
Copy the code

UMD

Compatible with AMD, CommonJS modular syntax.

UMD source code parsing

  (function(root, factory) {// Check whether AMD is supported (define exists)if (typeof define === 'function' && define.amd) {
        define(['b'], factory); // Whether the NodeJS module format is supported (exports exist)}else if (typeof module === 'object' && module.exports) {
        module.exports = factory(require('b')); // If the first two are not present, expose the module to the global (window or global)}else {
        root.returnExports = factory(root.b);
    }
  } (this, function (b) {
      // ...
  }));
Copy the code

import

Loading reference

  • Load at compile time (statically executed).
  • The reference is loaded
  • Cannot be in a code block
    • For compile time loading
      • Proposal presentation can be usedimport()Load while in use
  • Runtime loaded syntax such as expressions and variables cannot be used
    • Same as above

Webpack packaging strategy

Import is compiled into require/exports (CommonJS specification)

1. Direct introduction

Import xxx.js or import XXx. CSS is injected globally in the same way as adding

2. Commonjs synchronous syntax

Webpack will package require(‘abc.js’) into the file that references it. Get as an object.

3. Commonjs load asynchronously

Webpack (require.ensure) : Code splitting in WebPack 2.x.

There is A Modules/Async/A specification in CommonJS that defines the require.ensure syntax. Webpack implements this by sharding code at packaging time and asynchronously loading the sharded code.

At this point, list.js is packaged into a single chunk file. Like this: 1. D6f343b727f5923508bf. Js

For example: const Foo = () => import(‘./ foo.vue ‘)

manifest

The manifest file is the first to be loaded. The manifest file extracts parts that need to be changed frequently on the basis of vendor, and manages the running and loading of the bundle file through the manifest.js file. (for example, about asynchronously loading js modules)

Webpack V4.6.0 + adds support for prefetching and preloading

  import(/* webpackPrefetch: true* /'LoginModal'); <link rel= is generated"prefetch" href="login-modal-chunk.js"> and appends to the page headerCopy the code

It is not easy to organize, please like star,github.com/zhongmeizhi