concept
  • Encapsulate a complex program into several blocks (files) according to certain rules (specifications) and combine them together;
  • The internal data and implementation of a block are private, exposing only interfaces (methods) to communicate with other external modules.
Benefits of modularity
  • Avoid naming conflicts (reduce namespace pollution);
  • Better separation, loading on demand;
  • Higher reusability;
  • Higher maintainability.
Problems with the introduction of multiple script tags
  • Too many requests (too many dependent modules, too many requests);
  • Dependency ambiguity (do not know the specific dependency of the module, leading to loading sequence error);
  • Difficult to maintain (these two reasons can result).
//index.html
<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="jQuery.js"></script>
  <script src="module.js"></script>
</head>
<body>
  <div>123</div>
</body>
<script>
  myModule.foo();
  myModule.bar();
  console.log(myModule.data) ;
  myModule.data = 'xxxx';
  myModule.foo();
</script>
</html>
Copy the code
//module.js IIFE (anonymous function call); (function(window, $){
  let data = "www.baidu.com";
  function foo() {
    console.log(`foo() ${data}`);
    // Use the jQuery library
    $('body').css('background'.'red')}function bar() {
    console.log(`bar() ${data}`);
    otherFun();
  }
  function otherFun() {
    console.log(`otherFun()`);
  }
  window.myModule = { foo, bar }; }) (window, jQuery)
Copy the code
First, the CommonJS
  • NODE is based on the commonJS module specification. Each file is a module. Has its own scope; On the server side, module loading is synchronous; On the browser side, modules need to be compiled and packaged in advance

  • Features:

    • All code runs in the module scope and does not pollute the global scope;
    • Modules can be loaded multiple times, but only run once on the first load, and then the results are cached and read directly from the cache when they are loaded later. For the module to run again, the cache must be cleared.
    • The order in which modules are loaded, in the order they appear in the code.
  • Grammar:

    • Exposure module:js module.exports = valueorjs exports.xxx = value
    • Introduction module:js require('xxx')If the module is a third-party module, XXX indicates the module name. For a custom module, XXX is the module file path
  • The CommonJS specification states that within each module, the module variable represents the current module. This variable is an object whose exports property (module.exports) is the interface to the outside world. Loading a module loads the module.exports property of that module.

  • The require command is used to load module files. The basic function of the require command is to read and execute a JavaScript file and then return the exports object of that module. If no specified module is found, an error is reported.

  • The loading mechanism for CommonJS modules is that the input is a copy of the output value. That is, once a value is printed, changes within the module do not affect that value

Second, the AMD
  • AMD is better suited for browser-side asynchronous module loading than CommonJS synchronous module loading because AMD allows you to specify callback functions
  • The directory structure

  • Using the require. Js
<! -- index.html -->
<script src="https://cdn.bootcdn.net/ajax/libs/require.js/2.3.6/require.js"></script>
Copy the code
// Define a module1 module without dependencies
define('module1'.() = > {
  let count = 0;
  const add = () = > ++ count;
  const reset = () = > count = 0;
  const upperCase = string= > string.toUpperCase()

  return {
    add,
    reset,
    upperCase
  }
})
Copy the code
// Define a dependent module2 module that depends on Module1
define('module2'['module1'].(module1) = > {
  const showMsg = () = > module1.upperCase('hello-amd');

  return {
    showMsg
  }
})
Copy the code
<! -- Using modules in HTML files -->
<body>

<script>
  require.config({
    paths: {
      module1: './modules/module1'.module2: './modules/module2'}})require(['module1'.'module2'].(module1, module2) = > {
    console.log(module1.add()) / / 1
    console.log(module1.reset()) / / 0
    console.log(module2.showMsg()) //HELLO-AMD
  })
</script>
</body>
Copy the code
Third, CMD
  • CMD integrates the advantages of CommonJS and AMD. The CMD specification is specially used in the browser. The loading of modules is asynchronous, and modules will be loaded and executed only when they are used (on-demand loading is implemented, while AMD does not support on-demand loading).
  • The directory structure

  • The use of sea. Js
<script src="https://cdn.bootcdn.net/ajax/libs/seajs/3.0.3/sea.js"></script>
Copy the code
// Define the module module1
define((require.exports.module) = > {

  let string = 'I am a string';
  const readString = () = > 'module1 show() ' + string;

  // Exposed to the outside
  exports.readString = readString;
})
Copy the code
// Define the module module2
define((require.exports.module) = > {
  exports.msg = "Yes, I am."
})
Copy the code
// Define the module module
define((require.exports.module) = > {
  // Import dependent modules (synchronization)
  var module1 = require('./module1');
  console.log(module1.readString()) // module1 show() I am a string

  // Introduce dependency modules (asynchronous)
  require.async('./module2'.md2= > {
    console.log('This is introduced asynchronously:${md2.msg}`) // This is asynchronously introduced: it is me})})Copy the code
<! -- HTML file using module -->
<body>
<script>
  seajs.use('./modules/module')
</script>
Copy the code

4. ES6 modularity

  • The ES6 module is designed to be as static as possible, so that the module dependencies, as well as the input and output variables, can be determined at compile time. Both CommonJS and AMD modules can only determine these things at runtime.
  • Two key wordsimportandexport
    • The import import
    • Export export
//mian.js
export default {
  showMsg() {
    console.log('hahahahahah')}}export const msg = "It's time for love!"

//index.js
import module1 from "./module1"; // Corresponds to export default
module1.showMsg()
import { msg } from './module1'; / / the corresponding export
console.log(msg)

Do not use */
Copy the code