How is modularity implemented in JS?

小云云
Release: 2018-01-09 17:01:53
Original
2153 people have browsed it

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) }
Copy after login

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);
Copy after login
// add.js 文件 function add (a, b) { return a + b; } module.exports = add;
Copy after login

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; }
Copy after login

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)
Copy after login

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!