当前位置:网站首页>Touch your hand and bring you a commonjs specification
Touch your hand and bring you a commonjs specification
2022-07-04 04:23:00 【Careteen】
Node series - Previous section Details of the event cycle
Catalog
- Why is there modularity
- Prevent code name duplication Variables pollute the whole
- Too long , Uncomfortable to use
- How to realize modularization
- Closure
- The previous ones are abandoned AMD、CMD
- Modern use Node:CommonJs、es6:esModule
- CommonJs:node Main use
- How to roll one by yourself
- esModule
- To be improved
- CommonJs:node Main use
Why modularity is needed
With the development of the front end , Page effects 、 Interactions are implemented at the front-end level , The complexity of the front-end code logic increases . Writing code is impossible , Are written into a file , This is not readable and is not conducive to later maintenance . You need to use the idea of modules to divide the code , Make their responsibilities single and replaceable .
And we need to prevent variables from polluting the whole , Prevent renaming variables .
The development of modularity
Simply mention the development process of modularity from the introduction of the concept to today .
Define dependencies directly (1999)
Directly define dependencies and now popular CommonJs be similar , The difference is CommonJs Define a file, that is, a module , It can define modules in any file , Module and file are not associated .Dojo Thought .
namespace Pattern (2002)
Namespaces are mainly used to solve the problem of variable naming conflicts .YUI Thought .
Closure pattern (2003)
The introduction of closure pattern solves the problem of variable pollution .
Annotations define dependencies (2006)
Add some comments to the file header to mark the dependency of the file , Then resolve and introduce dependencies at compile time .
Dependency injection (2009)
Angular Introduced its idea .
CommonJs(2009)
Modern and popular modular solutions , from Node The end is then introduced into the front end . It is also a knowledge point that this article focuses on .
AMD(2009)
RequireJs Thought , The core is dependency preposition .
CMD( obsolete )
SeaJs Thought , The core is loading on demand . But Yubo doesn't maintain it now , It is equivalent to being abandoned .
UMD(2011)
Compatible with CommonJs and AMD, The core idea is if CommonJs In the environment , There is module.exports, non-existent define Give the function execution result to module.exports Realization CommonJs; Otherwise use AMD Environmental define.
Es6 Module(2015)
Modern modular solutions ,Node9+ Support , You can add flag--experimental-modules Use .
On the browser side, you can use <script type="module" src="xxx"></script> The way to use .
How to achieve a CommonJs standard
The focus of this article is to analyze CommonJs The core idea of norms .
The following codes are in the warehouse , Interested can Go to debugging
Breakpoint debugging as a starting point
First, we can debug through breakpoints require(path/to/file) Method as a starting point to understand the mechanism .
Two files are prepared 1.case.js and require.js
1.case.js The contents of the document
let info = require('./1.require.js')
console.log(info)require.js The contents of the document
module.exports = {
name: 'careteen',
age: '23'
}1、 Click on Enter function debugging Enter twice
2、 Into module.js Source file
There is a mod by Module Class , And provide a require Method , Enter the method to view
3、 First, I made some path assertions , Then return Module._load(), Pass the current file name into , Enter the method to view
4、 There is a cache function , Because this is the first time we load this file , There is no cache , So skip it
491 That's ok new One. Module example , stay 500 Line in tryModuleLoad Method , Then enter this method to check
5、 Make a layer try...catch, Actually call load Method , Then enter this method to check
6、 First, we will judge whether it has been loaded , Prevent duplicate loading .
1 The file name will be processed on the flag bit , We can... Again Debug console Input in this.paths Check the final processing result
In fact, it is to make a layer of judgment on the search , If the current directory does not have node_modules, Go to the upper level directory to find , Such a recursive . The specific implementation is shown in the figure below
2 The flag bit will get the extension of the file and process it according to the category , Access to Module._extensions() Check within the method
7、 Use fs.readFileSync() Method to synchronously read the contents of the file
Then call the instance's _compile Method , Enter the method to view
8、1 The flag bit will call the static method with the read content wrap Package
The wrapping method is shown in the figure below
The contents after the package are as follows
From the above, we can see that it is equivalent to using closures , Anonymous function passed in module Some properties on the instance exports/require/module...
In order to be in require Can read .
2 Flag bit used vm Built in module sandbox running code .
Its function is equivalent to eval('console.log(name)') and new Function('console.log(name)').
9、 The above steps are the general idea of modularization , Jump out of all the above methods .
10、 There are two other cases to consider when dealing with file types , The implementation principle is similar to .
It's just .json After reading the file, it will be converted into a JSON object .
Realize a simple modularization
Following the above ideas, we have roughly learned several core points of modularity
- cache , Improved read performance
- Search rules for processing files ( Detailed search rules will be given below )
- How to deal with the built-in module
- How does the third-party module handle
- How to deal with the file module
- adopt
fs.readFileSync()Read file contents - Handle
.js/json/nodeThree file types.jsThrough built-in modulesvmMake it sandbox the contents of the file.jsonAfter reading, it turns toJSON object.nodeIt's a binaryC++file , It can be run directly
Next, we will break through the above core points one by one
How to implement caching
Just hang a cache object
Search rules for processing files
A picture is worth a thousand words
Handle three file types
.js Package on the left layer of the document
.json After reading, it turns to JSON object
边栏推荐
- Leetcode skimming: binary tree 07 (maximum depth of binary tree)
- Idea modify body color
- Leetcode brush questions: binary tree 05 (flip binary tree)
- How was my life in 2021
- Confession code collection, who says program apes don't understand romance
- Keysight N9320B射频频谱分析仪解决轮胎压力监测方案
- (pointer) write a function to compare the size of strings by yourself, which is similar to StrCmp.
- There is a problem that the package cannot be parsed in the like project
- LevelDB源码解读-SkipList
- 【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
猜你喜欢

leetcode刷题:二叉树04(二叉树的层序遍历)

2020 Bioinformatics | TransformerCPI

指针数组和数组指针

资深开发人员告诉你,怎样编写出优秀的代码?

Leetcode brush questions: binary tree 05 (flip binary tree)

The difference between bagging and boosting in machine learning

leetcode刷题:二叉树08(N叉树的最大深度)

tdk-lambda电源主要应用

User defined path and file name of Baidu editor in laravel admin

Redis:集合Set类型数据的操作命令
随机推荐
深度优先搜索简要讲解(附带基础题)
资深开发人员告诉你,怎样编写出优秀的代码?
【CSRF-01】跨站请求伪造漏洞基础原理及攻防
网络 - VXLAN
[Huawei cloud IOT] reading notes, "Internet of things: core technology and security of the Internet of things", Chapter 3 (I)
SDP中的SPA
JS realizes the effect of text scrolling marquee
(pointer) write a function to compare the size of strings by yourself, which is similar to StrCmp.
Dry goods | detailed explanation of webshell Foundation
Flink学习6:编程模型
Huawei cloud Kunpeng engineer training (Guangxi University)
Pointer array and array pointer
分布式系统:what、why、how
Storage of MySQL database
普源DS1000Z系列数字示波器在通信原理实验中的应用方案
Ppt tutorial, how to save a presentation as a PDF file in PowerPoint?
干货!基于GAN的稀有样本生成
Tcp- simple understanding of three handshakes and four waves
RHCSA 06 - suid, sgid, sticky bit(待补充)
Msgraphmailbag - search only driveitems of file types