JavaScript in depth series (8): modular specification

Yuzhibo panghu 2021-01-21 04:51:15
javascript depth series modular specification

One 、 modular

1.1 What is a module

  1. Base a complex program on certain rules ( standard ) It's packaged into several pieces ( file ), And put them together
  2. The internal data and implementation of the block are private Of , It's just exposed to the outside ( Method ) Communicate with other external modules

1.2 Why modularity is needed

  1. Can cause naming conflicts and global pollution .
  2. Too many requests on the same page js File will cause page blocking and http Too many requests .

The early modularization adopt Closure In order to achieve Privatization of variables and modularization .

moduleA = function() {
var a,b;
return {
add: function (c){
return a + b + c;
 Copy code 

Two 、CommonJS

2.1 Basic concepts

CommonJS Specifications stipulated , Inside each module ,module Variable Represents the current module ( One js File is a module ). This variable is an object , its exports attribute ( namely module.exports) It's an external interface . Load a module , In fact, the module is loaded module.exports attribute .

Each file is a module , Has its own scope . Variables defined in a file 、 function 、 class , It's all private , Not visible to other files . On the server side , The module is loaded synchronously at runtime ; On the browser side , Modules need to be compiled and packaged in advance .
CommonJS The specification loading module is Sync Of , in other words , Only load complete , To perform the following operations .

Basic grammar :

  • Exposure module :module.exports = value or = value
  • Introduce modules :require(xxx), If it is Third-party module ,xxx by Module name ; If it is Custom module ,xxx by Module file path
var a = 1;
var b = function (){}
module.exports.a = a;
module.exports.b = b;
//require Method introduction
var main = require('./main')
 Copy code 

webpack It's often used in configuration ,webpack Is running on the node In the environment , He used CommonJS standard .

2.2 characteristic

  • All modules run in the scope of the module , It will not pollute the whole situation
  • The module runs many times , Only once , And then cache it , The only way to get the module to re execute is to clear the cache
  • He did it in the order of introduction , It's synchronous execution

Browser side module , Can't use Synchronous loading (synchronous), Only use Load asynchronously (asynchronous), This is it. AMD The context in which the specification was born .

3、 ... and 、AMD

3.1 Basic concepts

Loading modules asynchronously , Allows you to specify callback functions , The browser side generally uses AMD standard

AMD standard All modules and dependencies are specified in Load asynchronously , It looks like js Files are not One time Introduction 了 .

 // Define modules without dependencies
return modular
// Define dependent modules
define(['module1', 'module2'], function(m1, m2){
return modular
// Introduce use module
require(['module1', 'module2'], function(m1, m2){
// Use m1/m2
 Copy code 

3.2 characteristic

  1. Load on demand , That is to say, you only load the module when you import it , It doesn't load all at once on the page
  2. Load asynchronously , All loads are asynchronous , It doesn't block the page

3、 ... and 、CMD

Dedicated to the browser side , Module loading is asynchronous , Only when the module is used can it be loaded and executed


 // Define modules without dependencies
define(function(require, exports, module){ = value
module.exports = value
// Define dependent modules
define(function(require, exports, module){
// Introduce dependency modules ( Sync )
var module2 = require('./module2')
// Introduce dependency modules ( asynchronous )
require.async('./module3', function (m3) {
// Exposure module = value
// Introduce use module
define(function (require) {
var m1 = require('./module1')
var m4 = require('./module4')
 Copy code 

Four 、AMD And CMD difference

AMD( Such as require.js) To promote Rely on the pre - , Advance execution , Declare dependency at the front ,
In all dependence load perform complete after , To execute the main logic
Fast 、 Waste resources require branch : overall situation require And parts require
CMD( Such as sea.js) To promote Rely on proximity , What dependencies need to be resolved ,
In all dependence Loading finished after , encounter require Statement execution depends on
Save resources 、 Poor performance There is no overall situation require

AMD and CMD The biggest difference is right The execution timing of dependent modules is different , It's not when or how it's loaded , All two are Asynchronous load module .
AMD Rely on the pre - ,js It is easy to know who the dependency module is , Immediately load .
CMD To rely on , You need to turn the module into a string and parse it again to know which modules are dependent , That's a lot of criticism CMD A bit of , Sacrificing performance for ease of development , The actual parsing time for the module is short enough to ignore .
One sentence summary : Both are asynchronous loads , It's just that the timing of execution is different .AMD It's dependence on the front , Advance execution ,CMD It depends on nearby , Delay the .

5、 ... and 、UMD

UMD yes AMD and CommonJS The combination of

AMD modular With Browser first The principle of development , asynchronous Load module .
CommonJS modular With Server first Principle development , choice Sync load , Its modules don't need to be packaged (unwrapped modules).

UMD First judge whether you support Node.js Module (exports) Whether there is , To be is to use Node.js Module mode .
In the judgment of support AMD(define Whether there is ), To be is to use AMD Mode loading module .

 (function (window, factory) {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
} else {
window.eventUtil = factory();
})(this, function () {
//module ...
 Copy code 

6、 ... and 、ES6 modularization

ES6 The design idea of the module is to try to be static , Make it possible to determine module dependencies at compile time , And the input and output variables .CommonJS and AMD modular , They can only be identified at runtime . such as ,CommonJS Modules are objects , You have to look for object properties when you type .
ES6 Module Default is not currently supported by browsers , Need to use babel, Write everyday demo It's very common to throw mistakes when you're in trouble .

ES6 Module USES import Keyword import module ,export Keyword export module :

 /** How to export modules **/
var a = 0;
export { a }; // The first one is
export const b = 1; // The second kind
let c = 2;
export default { c }// The third kind of
let d = 2;
export default { d as e }// A fourth , Alias
/** How to import modules **/
import { a } from './a.js' // in the light of export Export mode ,.js Suffixes may be omitted
import main from './c' // in the light of export default Export mode , Use main.c
import 'lodash' // Just carry out lodash modular , But no value is entered
 Copy code 

7、 ... and 、ES6 Module and CommonJS Module differences

  1. CommonJS The output of the module is a copy of the value ,ES6 The module outputs a reference to a value

Once a value is output , Changes within the module do not affect this value . and ,CommonJS No matter how many times the module is loaded , Will only run once on the first load , Load later , All returned are caches of the results of the first run , Unless you manually clear the system cache .
JS When the engine statically analyzes the script , Module load command encountered import, It will generate a Read only references , Wait until the script actually executes , According to this read-only reference , Go to the loaded module to get the value . let me put it another way ,ES6 Of import It's kind of like Unix Systematic “ Symbolic connection ”, The original value has changed ,import The loaded value will also change . therefore ,ES6 The module is Dynamic reference , And it doesn't cache values , The variables in a module are bound to the module they are in .

  1. CommonJS Modules are run time loaded ,ES6 Module is a compile time output interface

CommonJ Loaded is a object ( namely module.exports attribute ), This object will only be generated after the script runs . That is to load the whole module before input , Generate an object , Then read the method from the object , This load is called Load at run time .

 // CommonJS modular
let { stat, exists, readFile } = require('fs');
// Equate to
let _fs = require('fs');
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;
 Copy code 

ES6 Module is not an object , Its external interface is just a static definition , It will be generated during the static parsing phase of the code . adopt export The command explicitly specifies the output code ,import In the form of static commands . That is to say import You can specify to load an output value , Instead of loading the entire module , This load is called Compile time loading perhaps Static loading .

 // ES6 modular
import { stat, exists, readFile } from 'fs';
 Copy code 

8、 ... and 、 summary

  1. CommonJS The specification is mainly used for Server programming , The loading module is Sync Of , This doesn't work in a browser environment , Because synchronization means blocking the load , Browser resources are loaded asynchronously , So there is AMD、CMD Solution .
  2. AMD Specification in Browser environment in Asynchronous load module , And it can be parallel Load multiple modules . however ,AMD The cost of standardized development is high , It is difficult to read and write the code , The semantics of module definition is not smooth .
  3. CMD Specification and AMD The norms are very similar , All for Browser programming , Rely on proximity , Delay the , It can be very easy in Node.js Run in . however , rely on SPM pack , Module loading logic bias .
  4. ES6 At the level of language standards , Module function is realized , And it's quite simple , It can completely replace CommonJS and AMD standard , Become a common module solution for browser and server .

Reference article

  1. Front end modularization details ( Full version )
  2. 【JS Basics 】 Understand the front-end modular specification
  3. 【 Depth and comprehensiveness 】 front end JavaScript Modular normative evolution 【 Very good , It's worth looking back 】
本文为[Yuzhibo panghu]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云