JavaScript modularity explained

JavaScript modularity explained

Preface:

1. Concept

  • Encapsulate a complex program into several blocks (files) according to certain rules (specifications) and combine them together;
  • The internal data and implementation of the block are private, and only some interfaces (methods) are exposed to the outside to communicate with other external modules.

2. The benefits of modularity

  • Avoid naming conflicts (reduce namespace pollution);
  • Better separation, loading on demand;
  • Higher reusability;
  • Higher maintainability.

3. Problems after introducing multiple script tags

  • Too many requests (too many dependent modules will result in too many requests);
  • Dependency ambiguity (the specific dependencies of the modules are unknown, resulting in incorrect loading order);
  • Difficult to maintain (the above two reasons will lead to this result).
//index.html
<!DOCTYPE html>
<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>


//module.js IIFE (anonymous function self-calling)
;(function(window,$){
  let data = "www.baidu.com";
  function foo() {
    console.log(`foo() ${data}`);
    //You need to use the jQuery library here $('body').css('background', 'red')
  }
  function bar() {
    console.log(`bar() ${data}`);
    otherFun();
  }
  function otherFun() {
    console.log(`otherFun()`);
  }
  window.myModule = { foo, bar };
})(window, jQuery)


1. CommonJS

  • NODE is based on the commonJS module specification. Each file is a module. It has its own scope. On the server side, the module is loaded synchronously. On the browser side, the module needs to be compiled and packaged in advance.

Features:

  • All code runs in the module scope and does not pollute the global scope;
  • A module can be loaded multiple times, but it will only be run once, the first time it is loaded, and the results of the run are cached. When it is loaded again, the cached results are read directly. To get the module working again, the cache must be cleared.
  • Modules are loaded in the order they appear in the code.

grammar:

  • Expose module: js module.exports = value or js exports.xxx = value
  • Import module: js require('xxx') If it is a third-party module, xxx is the module name; if it is a custom module, xxx is the module file path

The CommonJS specification stipulates that within each module, the module variable represents the current module. This variable is an object, and its exports attribute (i.e. module.exports) is the external interface. Loading a module actually loads the module.exports property of the 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 the module. If the specified module is not found, an error will be reported.

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

AMD

  • Compared with CommonJS's synchronous loading modules, AMD is more suitable for asynchronous module loading on the browser side because AMD allows the specification of callback functions.
  • Directory Structure

Using require.js

<!-- index.html -->
<script src="https://cdn.bootcdn.net/ajax/libs/require.js/2.3.6/require.js"></script>


//Define a module1 without dependencies define('module1', () => {
  let count = 0;
  const add = () => ++ count;
  const reset = () => count = 0;
  const upperCase = string => string.toUpperCase()

  return {
    add,
    reset,
    upperCase
  }
})


//Define a module2 with dependencies, which depends on module1
define('module2',['module1'], (module1) => {
  const showMsg = () => module1.upperCase('hello-amd');

  return {
    showMsg
  }
})


<!-- Use the module in the HTML file -->
<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>


3. CMD

  • CMD combines the advantages of CommonJS and AMD. The cmd specification is specifically used on the browser side. The module is loaded asynchronously and is loaded and executed only when the module is used (on-demand loading is realized, while AMD does not support on-demand loading)
  • Directory Structure

Using sea.js

<script src="https://cdn.bootcdn.net/ajax/libs/seajs/3.0.3/sea.js"></script>


//Define module module1
define((require, exports, module) => {

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

  //Exposing to the outside world exports.readString = readString;
})


//Define module module2
define((require, exports, module) => {
  exports.msg = "It is me"
})


//Define module
define((require, exports, module) => {
  //Introduce dependent modules (synchronous)
  var module1 = require('./module1');
  console.log(module1.readString()) // module1 show() I am a string

  //Introduce dependent modules (asynchronous)
  require.async('./module2', md2 => {
    console.log(`This is imported asynchronously: ${md2.msg}`) //This is imported asynchronously: It's me})
})


<!-- HTML file uses module -->
<body>
<script>
  seajs.use('./modules/module')
</script>


ES6 modularity

The design idea of ​​ES6 modules is 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 keywords import and export

  • import
  • export
//mian.js
export default {
  showMsg() {
    console.log('hahahahahah')
  }
}
export const msg = "It's a beautiful time with full moon and flowers!"

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

/*tips: Don't use <script type="module"> in HTML
import ....., there are cross-domain issues, you can download a plug-in in vscode, or start a local service to solve it, I will not go into details.
</script>*/

This is the end of this article about the detailed explanation of JavaScript modularization. For more relevant JavaScript modularization content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Modularity in Node.js, npm package manager explained
  • Detailed explanation of NodeJS modularity
  • How to understand JavaScript modularity
  • A brief discussion on several specifications of JS front-end modularization
  • Detailed explanation of the working principle and solution of Js modularization
  • Tutorial on exporting and importing in javascript to achieve modular management

<<:  Detailed explanation of Mysql's concurrent parameter adjustment

>>:  CSS cleverly uses gradients to achieve advanced background light animation

Recommend

Example of how to implement value transfer between WeChat mini program pages

Passing values ​​between mini program pages Good ...

Realization of real-time file synchronization between Linux servers

Usage scenarios For existing servers A and B, if ...

Web Design Tutorial (6): Keep your passion for design

<br />Previous article: Web Design Tutorial ...

Vue keeps the user logged in (various token storage methods)

Table of contents How to set cookies Disadvantage...

Creating private members in JavaScript

Table of contents 1. Use closures 2. Use ES6 clas...

How to use html table (to show the visual effect of web page)

We know that when using HTML on NetEase Blog, we ...

How to install Odoo12 development environment on Windows 10

Preface Since many friends say they don’t have Ma...

Advantages and disadvantages of common MySQL storage engines

Table of contents View all storage engines InnoDB...

Methods and steps for Etcd distributed deployment based on Docker

1. Environmental Preparation 1.1 Basic Environmen...

Comprehensive analysis of isolation levels in MySQL

When the database concurrently adds, deletes, and...

How to point the target link of a tag to iframe

Copy code The code is as follows: <iframe id=&...

How to remotely log in to the MySql database?

Introduction: Sometimes, in order to develop a pr...

Tutorial on installing phpMyAdmin under Linux centos7

yum install httpd php mariadb-server –y Record so...