


Why is modularity needed? Introduction to common modular solutions in js
This article brings you the content about why modularization is needed? An introduction to commonly used modular solutions in js has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Why modularization is needed
Before the emergence of ES6, the JS language itself did not provide modularization capabilities, which brought some problems to development, the most important of which Two problems should be global pollution and dependency management chaos.
// file a.js var name = 'aaa'; var sayName = function() { console.log(name); };
<!-- file index.html --> <script></script> <script> sayName(); // 'aaa' // code... var name = 'bbb'; sayName(); // 'bbb' </script>
In the above code, we called the sayName function provided by a.js twice and output different results. Obviously, this is because both files have assigned values to the variable name, so they cause each other had an impact. Of course, we can be careful not to define existing variable names when writing code, but when a page references a dozen files with several hundred lines, it is obviously not realistic to remember all the variables that have been defined.
// file a.js var name = getName(); var sayName = function() { console.log(name) };
// file b.js var getName = function() { return 'timo'; };
<script></script> <script></script> <script> sayName(); // 'timo' </script>
<script></script> <script></script> // Uncaught ReferenceError: getName is not defined
The above code shows that when multiple files have dependencies, we need to ensure the order in which they are introduced, so as to ensure that when running a certain file, its dependencies have been loaded in advance. It is conceivable that in the face of larger files, project, the more dependencies we need to deal with, which is cumbersome and error-prone.
In order to solve these problems, many specifications have emerged in the community that provide modular capabilities for the JS language. With the help of these specifications, our development can be made more convenient and safer.
Common modularization solutions
CommonJS
CommonJS is one of the modularization solutions proposed by the community, and Node.js follows this set plan.
Basic writing method
// file a.js var obj = { sayHi: function() { console.log('I am timo'); }; }; module.exports obj;
// file b.js var Obj = require('xxx/xxx/a.js'); Obj.sayHi(); // 'I am timo'
In the above code, file a.js is the provider of the module, and file b.js is the caller of the module.
Specification
Each file is a module;
provided within the modulemodule Object, representing the current module;
The module uses exports to expose its own functions/objects/variables, etc.;
The module imports other modules through the require() method; the specifications of
CommonJS are simply the above 4 items. You can understand it by referring to the examples in the basic writing method. , in actual implementation, although Node.js follows the CommonJS specification, it still makes some adjustments to it.
AMD
AMD is one of the modular specifications, and RequireJS follows this set of specifications.
Basic usage
// file a.js define('module', ['m', './xxx/n.js'], function() { // code... })
In the above code, the file a.js exports the module;
Specification
In AMD, the exposed module uses define Function
define(moduleName, [], callback);
As shown in the above code, the define function has three parameters
moduleName. This parameter can be omitted, indicating the name of the module. Generally, it has little effect
['name1', 'name2'], the second parameter is an array, indicating other modules that the current module depends on. If there are no dependent modules, this parameter can be omitted
callback, the third parameter is a required parameter, it is a callback function, the inside is the relevant code of the current module
Others
Features of ADM It is dependency front-loading. This is the biggest difference between the ADM specification and the CMD specification to be introduced next. Dependency front-loading means: before running the callback of the currently loaded module, all dependent packages will be loaded first, which is the third step of the define function. The dependent packages specified in the two parameters.
CDM
Basic writing method
define(function(require, exports, module) { var a = require('./a') a.doSomething(); // code... var b = require('./b') // code... })
The above code is the basic writing method of the CMD specification export module;
Specification
It can be seen from the writing method It turns out that the writing method of CMD is very similar to that of AMD. The main difference is the difference in dependency loading timing. As mentioned above, AMD is dependent on front-end, while the CMD specification advocates the proximity principle. Simply put, dependencies are not loaded before the module is run. , during the running of the module, when a certain dependency is needed, load it again.
UMD
When CommonJS, AMD, and CMD are in parallel, a solution is needed that is compatible with them, so that when we develop, we no longer need to consider the specifications followed by dependent modules. , and the emergence of UMD is to solve this problem.
Basic writing method
(function (root, factory) { if (typeof define === 'function' && define.amd) { //AMD define(['jquery'], factory); } else if (typeof exports === 'object') { //Node, CommonJS之类的 module.exports = factory(require('jquery')); } else { //浏览器全局变量(root 即 window) root.returnExports = factory(root.jQuery); } }(this, function ($) { //方法 function myFunc(){}; //暴露公共方法 return myFunc; }));
The above code is the basic writing method of UMD. As can be seen from the code, it can support both the CommonJS specification and the AMD specification.
ES6 module
The above introduces CommonJS, AMD, CMD and UMD respectively. They are all contributions of the community to the modularization of JS. The fundamental reason for the emergence of this specification is the JS language. It has no modularity capabilities. At present, the latest language specification ES6 of JS has added modularity capabilities to JS. JS’s own modularization solution can completely replace the various specifications currently proposed by the community, and can Commonly used on the browser side and Node side.
The modularization capability in ES6 consists of two commands: export and import. The export command is used to specify the external interface of the module. The import command is used to import functions provided by other modules.
export command
A file in ES6 is a module. The variables/functions inside the module are inaccessible from the outside. If you want to expose the internal functions/variables to other modules, To use it, you need to export it through the export command
// file a.js export let a = 1; export let b = 2; export let c = 3;
// file b.js let a = 1; let b = 2; let c = 3; export {a, b, c}
// file c.js export let add = (a, b) => { return a + b; };
上面三个文件的代码,都是通过export命令导出模块内容的示例,其中a.js文件和b.js文件都是导出模块中的变量,作用完全一致但写法不同,一般我们更推荐b.js文件中的写法,原因是这种写法能够在文件最底部清楚地知道当前模块都导出了哪些变量。
import命令
模块通过export命令导出变量/函数等,是为了让其他模块能够导入去使用,在ES6中,文件导入其他模块是通过import命令进行的
// file d.js import {a, b, c} from './a.js';
上面的代码中,我们引入了a.js文件中的变量a、b、c,import在引入其他模块内的函数/变量时,必须与原模块所暴露出来的函数名/变量名一一对应。
同时,import命令引入的值是只读的,如果尝试对其进行修改,则会报错
import {a} d from './a.js'; a = 2; // Syntax Error : 'a' is read-only;
export default命令
从上面import的介绍可以看到,当需要引入其他模块时,需要知道此模块暴露出的变量名/函数名才可以,这显然有些麻烦,因此ES6还提供了一个import default命令
// file a.js let add = (a, b) => { return a+b }; export default add;
// file b.js import Add from './a.js'; Add(1, 2); // 3
上面的代码中,a.js通过export default命令导出了add函数,在b.js文件中引入时,可以随意指定其名称
export default命令是默认导出的意思,既然是默认导出,显然只能有一个,因此每个模块只能执行一次export default命令,其本质是导出了一个名为default的变量或函数。
The above is the detailed content of Why is modularity needed? Introduction to common modular solutions in js. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.