How is modularity implemented in JS?
Due to the initial positioning of JS (I did not expect it to be used in overly complex scenarios at the beginning), it does not provide a module system. As applications become more complex, modularization becomes a problem that must be solved. In line with the principle of Feimai's in-depth principles, it is necessary to lift the veil of modularization. This article mainly introduces how modularization in Js is implemented in detail, and introduces the operation of modularization in detail, which has certain reference value. Those who are interested can learn more, I hope it can help everyone.
1. Problems that need to be solved by modularization
To conduct an in-depth analysis of something, it is necessary to look at it with a purpose. The problem to be solved by modularization can be summarized in one sentence
Better organize project code without global pollution
To give a simple chestnut, we now have the following Code:
function doSomething () { const a = 10; const b = 11; const add = function (a + b) { return a + b } add (a + b) }
In real application scenarios, doSomething may need to do many, many things, and the add function may be more complex and can be reused, so we hope to separate the add function into a separate file, then:
// doSomething.js 文件 const add = require('add.js'); const a = 10; const b = 11; add(a+ b);
// add.js 文件 function add (a, b) { return a + b; } module.exports = add;
The purpose of this is obvious, to better organize the project code, notice the require and module.exports in the two files, from the current God's perspective, this comes from CommonJS The keywords in the specification (there will be a chapter dedicated to the specification later) represent import and export respectively. Regardless of the specification, this is actually a problem that needs to be solved on our road to modularization. In addition, although the add module needs to be reused, we do not want to cause global pollution when introducing add
2. How to run the imported module
In the above example, we have The code is split into two module files. How can we implement require so that the code in the example can run normally without causing global pollution?
Ignoring the loading process of the module file code, assuming that require can already read the code string from the module file, then require can be implemented like this
function require (path) { // lode 方法读取 path 对应的文件模块的代码字符串 // let code = load(path); // 不考虑 load 的过程,直接获得模块 add 代码字符串 let code = 'function add(a, b) {return a+b}; module.exports = add'; // 封装成闭包 code = `(function(module) {$[code]})(context)` // 相当于 exports,用于导出对象 let context = {}; // 运行代码,使得结果影响到 context const run = new Function('context', code); run(context, code); //返回导出的结果 return context.exports; }
There are several key points:
1) In order not to cause global pollution, the code string needs to be encapsulated in the form of a closure, and the keyword module.exports should be exported. The module is the only carrier to contact the outside world and needs to be used as a closure. The input parameters of the anonymous function are associated with the context passed by the referrer
2) Use new Function to execute the code string. It is estimated that most students are not familiar with new Function because it is generally There is no need to do this when defining a function. You must know that you can directly create a function using the Function class. The syntax is as follows:
var function_name = new function(arg1, arg2, ..., argN, function_body)
In the above form, each arg is a parameter, and the last parameter is the function body ( code to be executed). These parameters must be strings. In other words, you can use it to execute string code, similar to eval, and compared to eval, you can also pass in the values of certain variables in the string code in the form of parameters
3 ) If you have ever wondered why the standard export keyword is only exports but we use module.exports in actual use (it should be familiar to those who have written Node code), then you can find the answer in this code , if you only use exports to receive context, then reassigning exports will not have any impact on context (the address of the parameter is passed). If you don’t believe it, change the code to the following form and run it again:
Demonstration results
3. Code loading method
solves the problem of running the code, and also needs to solve the problem of loading the module file code. According to the above example, our The goal is to load the module file code in the form of a string
In the Node container, all module files are local. You only need to read the module file from the local disk and load the string code, and then follow the above steps The process is fine. Facts have proved that the loading and execution method of Node's non-built-in, core, and c++ modules is roughly the same (although it is not new Function, it is a similar method)
In the RN/Weex container, you need to load a For remote bundle.js, you can request a remote js file through Native capabilities, and then read it into a string code and load it (according to this logic, it seems that Node can read a remote js module, although in most cases We don’t need to do this next)
In the browser environment, all Js modules need to be read remotely. The embarrassing thing is that, limited by the capabilities provided by the browser, it cannot be streamed through ajax in the form of files. Read the remote js file directly into string code. If the prerequisites cannot be met, the above operation strategy will not work, and we can only find another way
This is why there is a CommonJs specification, and why there are AMD/CMD specifications
So How to do it on the browser? To dynamically load a remote Js module file through Js control in the browser, you need to dynamically insert a

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

I'm really sorry that I can't provide real-time programming guidance, but I can provide you with a code example to give you a better understanding of how to use PHP to implement SaaS. The following is an article within 1,500 words, titled "Using PHP to implement SaaS: A comprehensive analysis." In today's information age, SaaS (Software as a Service) has become the mainstream way for enterprises and individuals to use software. It provides a more flexible and convenient way to access software. With SaaS, users don’t need to be on-premises

Title: Detailed explanation of data export function using Golang. With the improvement of informatization, many enterprises and organizations need to export data stored in databases into different formats for data analysis, report generation and other purposes. This article will introduce how to use the Golang programming language to implement the data export function, including detailed steps to connect to the database, query data, and export data to files, and provide specific code examples. To connect to the database first, we need to use the database driver provided in Golang, such as da
