preface

In order to the future, may need to do the old project, I also want to play, so make up for the old era of modular gameplay…

Code: Github address

AMD/CMD/Common/js/UMD ES6 modular main difference

Previously (before 2019, before 2019) front-end modularization, the mainstream is AMD/CommonJS, UMD support both can be used

Why modular?

  • One of the pain points of front-end development has always been code reuse/responsibility division. Compatibility such as support/componentization/code compression for new syntaxes such as ES6 is beyond the scope of this article.
  • In theseFront-end modularizationIt was used before the advent of the<script>Tags introducedjsIf every page isBy module(such as all variable methods in one object) does not cause global variable pollution, but variousJs/moduleThe dependency relationship is not clear, and some temporarily unavailable JS, and will be downloaded first, affecting the page loading speed.

Synchronous/asynchronous, static/dynamic

  • Synchronous: CMD/CommonJS/ES6import
  • Asynchronous: AMD/CMDrequire.async
  • Static: execute at compile time; AMD/ES6import.
  • Dynamic: runtime execution; CMD/CommonJS/ES6+import()

Operating environment:

  • Browser: AMD/CMD, ES6 modular Currently the browser is not native support, need to use Webpack/Babel compiled into the browser supported version
  • Server: CommonJS: the modular specification used by Node.js

UMD:

  • Support AMD/CommonJS unified specification, using modules defined by UMD, can support AMD and CommonJS

Third Party library:

  • Libraries that support UMD can be used on AMD/CommonJS, CMD is a bit behind on this;
  • If you like CommonJS, CMD is a good choice

A, AMD/require. Js

What is AMD?

  • AMD: Asynchronous Module Definition
  • Dependency prefixes are introduced for define and then used as arguments to the callback function
  • There is more support for third-party libraries than there is for CMD, such as the lodash.js library used here (or I didn’t configure it…).
  • usereturnIs derived from

The following example uses require.js v2.3.6:

Directory structure:

. \ the require js - AMD ├ ─ index. The HTML ├ ─ js ├ ─ lodash. Js ├ ─ m1. Js └ ─ m2. The js ├ ─ main. Js └ ─ the require. JsCopy the code

HTML

<script src="./require.js" data-main="./main.js"></script>
Copy the code

The main entrance. Js

// js/mian.js
// Global configuration
require.config({
  // Root path Settings, paths below are all set according to baseUrl paths
  baseUrl:'./js'.paths: { // Define the path corresponding to the reference name
    m1: 'm1'.m2: 'm2'.lodash: 'lodash'
  },
  // Used to configure incompatible modules, no third party library for module.exports.
  // shim:{
  // 'lodash': {
  // exports: '_'
  / /}
  // }
})

define('main'.function() {
  require(['m1'].function(m1) {
    console.log('name: ', m1.name);
    console.log('add: ', m1.add(2.8));
  });
})

Copy the code

The module definition

Define (id? , dependencies? , factory);

// js/m1.js
// define(id? , dependencies? , factory);
define('m1'['lodash'.'m2'].function(_, m2) {
  
  _.map([1.2].function(num){
    console.log('num: ', num);
  });

  console.log(m2);

  var add = function(x, y) {
    return x + y;
  };

  return {
    name: 'm1.js'.add: add
  };
})

Copy the code

Second, CMD/sea. Js

What is CMD?

  • On the browser sideCommonJS(excluding some node.js environment-specific apis); Synchronous and dynamic loading;
  • Rely on nearbyWhere need whererequire;
  • Asynchronous introducedrequire.async([dependencies], callback);
  • useexports/module.exportsWay to export

The following example uses sea-.js v3.0.0:

Directory structure:

. \sea.js-- ├─ index.html ├─ ├─ m1.js ├─ class.js ├─ class.js ├─ class.js ├─ class.js ├─ class.jsCopy the code

HTML

  <script src="./js/lodash.js"></script>
  <script src="./sea.js"></script>
  <script>
    / / configuration
    seajs.config({
      base: '/'.// Subsequent references are based on this path
      alias: {  // Alias, which can be replaced by a name (based on the base path)
        lodash: 'js/lodash.js',
        m1: 'js/m1',
        m2: 'js/m2',}});// Load the entry module
    seajs.use("./main.js".function(main) {
      // callback after performing the synchronization operation before the main.js export (exports/module.exports)
      main.init(); // init
    });

  </script>
Copy the code

The main entrance. Js

// js/mian.js
define(function(require, exports, module) {
  var m1 = require('m1');
  console.log(m1.add(2.8));

  // Export separately
  exports.init = function init() {
    console.log('init');
  }

  // Or define it first and then export it uniformly
  // function init() {
  // console.log('init');
  // }
  // module.exports = {
  // init: init
  // }
});

Copy the code

The module definition

Define (function(require, exports, module) {})

// js/m1.js
define(function(require, exports, module) {
  // Use the third-party library lodash.js, script tag import
  // require first, otherwise use script
  _.map([1.2].function(item) {
    console.log(item);
  })

  // Async import
  require.async('m2'.function(m2) {
    console.log('Asynchronously introduce m2');
  }); // m2

  // Each function is exported separately
  exports.add = function(x, y) {
    return x + y;
  }

  // Or define it first and then export it uniformly
  // function add(x, y) {
  // return x + y;
  // }
  // modules.exports = {
  // add: add
  // }
});

Copy the code