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.
[Related recommendations: javascript video tutorial, web front-end】
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.
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.
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.
1. The simplest and crudest way
function fn1(){ // ... } function fn2(){ // ... }
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(){ // ... } }
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。这不仅避免了外界访问此 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)
历史上,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!