当前位置:网站首页>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/node
Three file types.js
Through built-in modulesvm
Make it sandbox the contents of the file.json
After reading, it turns toJSON object
.node
It'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
边栏推荐
- *. No main manifest attribute in jar
- Katalon使用script实现查询List大小
- How to telecommute more efficiently | community essay solicitation
- idea修改主体颜色
- 10 reasons for not choosing to use free virtual hosts
- leetcode 121 Best Time to Buy and Sell Stock 买卖股票的最佳时机(简单)
- dried food! Generation of rare samples based on GaN
- 思考的小记录
- Lnk2038 detected a mismatch of "runtimelibrary": the value "md_dynamicrelease" does not match the value "mdd_dynamicdebug" (in main.obj)
- 01 QEMU starts the compiled image vfs: unable to mount root FS on unknown block (0,0)
猜你喜欢
Lnk2038 detected a mismatch of "runtimelibrary": the value "md_dynamicrelease" does not match the value "mdd_dynamicdebug" (in main.obj)
软件测试是干什么的 发现缺陷错误,提高软件的质量
Confession code collection, who says program apes don't understand romance
Flink learning 7: application structure
PostgreSQL users cannot create table configurations by themselves
Two commonly used graphics can easily realize data display
北漂程序员,月薪20K,一年攒15W,正常吗?
Flink learning 6: programming model
Leetcode skimming: binary tree 09 (minimum depth of binary tree)
透过JVM-SANDBOX源码,了解字节码增强技术原理
随机推荐
2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
毕业设计:设计秒杀电商系统
C language bidirectional linked list first edition
Parameterization of controls in katalon
leetcode刷题:二叉树06(对称二叉树)
Exercises in quantum mechanics
RHCSA 04 - 进程管理
The maximum expiration time of client secret in azure ad application registration is modified to 2 years
Flink学习6:编程模型
华为云鲲鹏工程师培训(广西大学)
STM32外接DHT11显示温湿度
leetcode刷题:二叉树04(二叉树的层序遍历)
Getting started with the go language is simple: go implements the Caesar password
How to telecommute more efficiently | community essay solicitation
Ppt tutorial, how to save a presentation as a PDF file in PowerPoint?
tdk-lambda电源主要应用
RHCSA 03 - 文件的基础权限
The three-year revenue is 3.531 billion, and this Jiangxi old watch is going to IPO
Confession code collection, who says program apes don't understand romance
Tcp- simple understanding of three handshakes and four waves