当前位置:网站首页>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)
- [microservice openfeign] @feignclient detailed explanation
- RHCSA 04 - 进程管理
- RHCSA 06 - suid, sgid, sticky bit(待补充)
- (pointer) write a function to compare the size of strings by yourself, which is similar to StrCmp.
- Flink learning 8: data consistency
- Redis cluster uses Lua script. Lua script can also be used for different slots
- 一位毕业生的自我分享
- [microservices openfeign] two degradation methods of feign | fallback | fallbackfactory
- Katalon uses script to query list size
猜你喜欢

指针数组和数组指针

干货!基于GAN的稀有样本生成

There is a problem that the package cannot be parsed in the like project

Ppt tutorial, how to save a presentation as a PDF file in PowerPoint?

北漂程序员,月薪20K,一年攒15W,正常吗?

2021 RSC | Drug–target affinity prediction using graph neural network and contact maps

三年进账35.31亿,这个江西老表要IPO了

Distributed system: what, why, how

如何远程办公更有效率 | 社区征文

What does software testing do? Find defects and improve the quality of software
随机推荐
Global exposure and roller shutter exposure of industrial cameras
(指针)自己写一个比较字符串大小的函数,功能与strcmp类似。
微信脑力比拼答题小程序_支持流量主带最新题库文件
Flink learning 8: data consistency
Myslq delete followed by limit
微信公众号无限回调授权系统源码
One click compilation and deployment of MySQL
How to add custom API objects in kubernetes (1)
Idea modify body color
TCP-三次握手和四次挥手简单理解
10 reasons for not choosing to use free virtual hosts
华为云鲲鹏工程师培训(广西大学)
2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
批处理初识
ctf-pikachu-XSS
Huawei cloud Kunpeng engineer training (Guangxi University)
How was my life in 2021
仿《游戏鸟》源码 手游发号评测开服开测合集专区游戏下载网站模板
2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
Confession code collection, who says program apes don't understand romance