Table of Contents
Background
The concept of modules
Benefits of modularity
A brief history of modularization
实现模块化的方案规范总览
Home Web Front-end JS Tutorial Advantages of Module modular programming (summary sharing)

Advantages of Module modular programming (summary sharing)

Aug 08, 2022 pm 04:06 PM
javascript es6

This article brings you relevant knowledge about javascript, which mainly introduces the advantages of Module modular programming. As the front-end functions become more and more complex, the front-end code becomes increasingly expanded. In order to reduce To reduce maintenance costs and improve code reusability, front-end modularization is imperative. Let’s take a look at it together. I hope it will be helpful to everyone.

Advantages of Module modular programming (summary sharing)

[Related recommendations: javascript video tutorial, web front-end

Background

As front-end functions become more and more complex, front-end code expands day by day. In order to reduce maintenance costs and improve code reusability, front-end modularization is imperative.

All js files are introduced in one html, causing the following adverse effects:

  • Too many requests. First of all, we have to rely on multiple modules, which will send multiple requests, resulting in too many requests

  • Dependency ambiguity. We don’t know what their specific dependencies are, which means it’s easy to make errors in the loading sequence because we don’t understand the dependencies between them.

  • Difficult to maintain. The above two reasons make it difficult to maintain, and it is very likely that one thing will affect the whole body, causing serious problems in the project.

The concept of modules

is defined in webpack as follows:

In modular programming, developers decompose the program into discrete functional blocks ( discrete chunks of functionality), and are called modules. Each module has a smaller contact surface than a complete program, making verification, debugging, and testing a breeze. Well-written modules provide solid abstraction and encapsulation boundaries so that each module in the application has a coherent design and a clear purpose.

Modules should be discrete functional blocks with single responsibilities, independent of each other, low coupling, high cohesion and replaceability.

The concept of modularity

Modularization is a way to decompose complex systems into better manageable modules. It can divide the system code into a series of With single-responsibility, highly decoupled and replaceable modules, it will become obvious how changes in one part of the system will affect other parts, making the system maintainability simpler and easier to achieve.

Modularization is a divide-and-conquer idea that achieves fine-grained control by decomposing complex systems into independent modules, which is very beneficial to the maintenance and management of complex systems. Modularity is also the cornerstone of componentization and a prerequisite for today's colorful front-end world.

Why modularization is needed

The main difference between front-end development and other development work is that the front-end is based on multi-language and multi-level coding and organizational work; Product delivery is based on the browser. These resources are run to the browser through incremental loading. How to organize these fragmented codes and resources in the development environment and ensure that they are loaded quickly and elegantly on the browser side? To update, a modular system is needed.

Benefits of modularity

  • Maintainability. Because modules are independent, a well-designed module will make the outside code less dependent on itself, so that it can be updated and improved independently.

  • Namespaces. In JavaScript, if a variable is declared outside the top-level function, it becomes globally available. Therefore, naming conflicts often occur accidentally. Using modular development to encapsulate variables can avoid polluting the global environment.

  • Reuse code. We sometimes like to copy code from previously written projects to new projects. This is no problem, but a better way is to avoid duplicating code bases through module references. After updating the module, we can update all projects that reference the module simultaneously and specify the version number to avoid the trouble caused by API changes.

A brief history of modularization

1. The simplest and crudest way

function fn1(){
  // ...
}
function fn2(){
  // ...
}
Copy after login

Introduce files through script tags and call related functions. This requires manual management of the dependency order, which can easily cause naming conflicts and pollute the overall situation. As the complexity of the project increases, the maintenance cost becomes higher and higher.

2. Use objects to simulate namespaces

var output = {
  _count: 0,
  fn1: function(){
    // ...
  }
}
Copy after login

This can solve the above global pollution problem. It has some meaning of namespace, but as the complexity of the project increases, the need for more and more There are so many such objects that need to be maintained. If nothing else, naming them is a problem. The most important thing is that the internal properties can still be directly accessed and modified.

3. Closure

var module = (function(){
  var _count = 0;
  var fn1 = function (){
    // ...
  }
  var fn2 = function fn2(){
    // ...
  }
  return {
    fn1: fn1,
    fn2: fn2
  }
})()
module.fn1();
module._count; // undefined
Copy after login

这样就拥有独立的词法作用域,内存中只会存在一份 copy。这不仅避免了外界访问此 IIFE 中的变量,而且又不会污染全局作用域,通过 return 暴露出公共接口供外界调用。这其实就是现代模块化实现的基础。

4. 更多

还有基于闭包实现的松耦合拓展、紧耦合拓展、继承、子模块、跨文件共享私有对象、基于 new 构造的各种方式,这种方式在现在看来都不再优雅。

// 松耦合拓展
// 这种方式使得可以在不同的文件中以相同结构共同实现一个功能块,且不用考虑在引入这些文件时候的顺序问题。
// 缺点是没办法重写你的一些属性或者函数,也不能在初始化的时候就是用module的属性。
var module = (function(my){
  // ...
  return my
})(module || {})
// 紧耦合拓展(没有传默认参数)
// 加载顺序不再自由,但是可以重载
var module = (function(my){
  var old = my.someOldFunc
  
  my.someOldFunc = function(){
    // 重载方法,依然可通过old调用旧的方法...
  }
  return my
})(module)
Copy after login

实现模块化的方案规范总览

历史上,JavaScript 一直没有模块(module)体系,无法将一个大程序拆分成互相依赖的小文件,再用简单的方法拼装起来。其他语言都有这项功能,比如 Ruby 的require、Python 的import,甚至就连 CSS 都有@import,但是 JavaScript 任何这方面的支持都没有,这对开发大型的、复杂的项目形成了巨大障碍。

在 ES6 之前,社区制定了一些模块加载方案,最主要的有 CommonJS 和 AMD 两种。前者用于服务器,后者用于浏览器。ES6 在语言标准的层面上,实现了模块功能,而且实现得相当简单,完全可以取代 CommonJS 和 AMD 规范,成为浏览器和服务器通用的模块解决方案。

ES6 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。CommonJS 和 AMD 模块,都只能在运行时确定这些东西。比如,CommonJS 模块就是对象,输入时必须查找对象属性。

目前实现模块化的规范主要有:

  • CommonJS

CommonJS 是以在浏览器环境之外构建 JavaScript 生态系统为目标而产生的项目,比如在服务器和桌面环境中。

采用同步加载模块的方式,也就是说只有加载完成,才能执行后面的操作。CommonJS 代表:Node 应用中的模块,通俗的说就是你用 npm 安装的模块。

它使用 require 引用和加载模块,exports 定义和导出模块,module 标识模块。使用 require 时需要去读取并执行该文件,然后返回 exports 导出的内容。

  • CMD

CMD(Common Module Definition)

CMD是SeaJS在推广过程中生产的对模块定义的规范,在Web浏览器端的模块加载器中,SeaJS与RequireJS并称,SeaJS作者为阿里的玉伯。

CMD规范专门用于浏览器端,模块的加载是异步的,模块使用时才会加载执行。CMD规范整合了CommonJS和AMD规范的特点。在 Sea.js 中,所有 JavaScript 模块都遵循 CMD模块定义规范。

  • AMD

AMD(Asynchronous Module Definition)

异步模块定义,所谓异步是指模块和模块的依赖可以被异步加载,他们的加载不会影响它后面语句的运行。有效避免了采用同步加载方式中导致的页面假死现象。AMD代表:RequireJS。

AMD一开始是CommonJS规范中的一个草案,全称是Asynchronous Module Definition,即异步模块加载机制。后来由该草案的作者以RequireJS实现了AMD规范,所以一般说AMD也是指RequireJS。

RequireJS是一个工具库,主要用于客户端的模块管理。它的模块管理遵守AMD规范,RequireJS的基本思想是,通过define方法,将代码定义为模块;通过require方法,实现代码的模块加载。

  • ES6模块

ES6模块的设计思想,是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。所以说ES6是编译时加载,不同于CommonJS的运行时加载(实际加载的是一整个对象),ES6模块不是对象,而是通过export命令显式指定输出的代码,输入时也采用静态命令的形式。

ES6 的模块自动采用严格模式,不管你有没有在模块头部加上”use strict”;。

严格模式主要有以下限制。

  • 变量必须声明后再使用

  • 函数的参数不能有同名属性,否则报错

  • 不能使用with语句

  • 不能对只读属性赋值,否则报错

  • 不能使用前缀 0 表示八进制数,否则报错

  • 不能删除不可删除的属性,否则报错

  • 不能删除变量delete prop,会报错,只能删除属性delete global[prop]

  • eval不会在它的外层作用域引入变量

  • eval和arguments不能被重新赋值

  • arguments不会自动反映函数参数的变化

  • 不能使用arguments.callee

  • 不能使用arguments.caller

  • 禁止this指向全局对象

  • Cannot use fn.caller and fn.arguments to obtain the stack of function calls

  • Added reserved words (such as protected, static and interface)

Modules must comply with the above restrictions.

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of Advantages of Module modular programming (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles