当前位置:网站首页>Common JS modular specification from a code question
Common JS modular specification from a code question
2022-07-23 14:52:00 【Flying birds on Mars】
CommonJS
stay node.js in , Use CommonJS As its modular specification .
according to CommonJS Modular specification , A single JS File is a module , Each module is a separate one Scope , Variables defined inside the module , Cannot read in other modules . If you want to communicate between modules , You need to use the export and import syntax of the module :
- Module through variable
exportsOutward exposureAPI, Be careful ,exportsIt can only be one object , The properties of the object are exposedAPI. - In another module , Through global functions
requireImport exported from other modulesexportsobject .
Basic grammar
for example ,a.js Export objects from file exports, Which includes name、add attribute , They are constants defined in the file .
const name = 'Jack';
const add = (a, b) => a + b;
module.exports = {
name,
add
};
In the file b.js in , Through global functions require Import the exported object exports.
const api = require('./a');
console.log(api);
// { name: 'Jack', add: [Function: add] }
Be careful ,api This can be taken at will . Usually , It can also be done through Deconstruct assignment In the form of , Import on demand :
const {
name } = require('./a');
console.log(name);
// Jack
Multiple import
Follow the example above , If in b.js In file , Multiple import a modular , What will happen ? Is the same object imported twice ?
const api1 = require('./a');
const api2 = require('./a');
console.log(api1 === api2);
// true
As shown in the above code ,b.js Introduced twice in a modular , And judge whether the two imported variables are equal . Results output true, Explain that if you quote more than once , In fact, the imported module is the same object .
actually , In the first import , Will execute the file to be imported , And cache an object in memory , among exports Is the object to import . When importing the same module again , It will not be implemented anymore , Will get this directly from memory exports object .
{
id: '...', // Module name
exports: {
... }, // Interface of module output
loaded: true, // Whether the script of the module is finished
...
}
Whether changes are supported
The import module , In fact, it is to execute the module to be imported , And then the output of exports object , As require The return value of the function . It's actually ordinary Assignment statement , If you use var、let Make a statement , Of course, changes are supported .
let api1 = require('./a');
api1 = {
};
console.log(api1);
// {}
Circular reference
If a module is loaded circularly , Output only the executed part , Unexecuted will not output .
If in a.js Introduction in b.js, stay b.js Introduction in a.js, Form a circular reference , Will it be wrong to report ? If no error is reported , What is the result of the operation ?
It is clear to take code as an example . As shown in the following code ,a Module introduction b modular ,b Module introduction a modular .
// a.js
const b = require('./b');
console.log('b', b);
const name = 'Jack';
const age = 18;
module.exports = {
name,
age
};
// b.js
const a = require('./a');
console.log('a', a);
const id = '001';
module.exports = {
id
};
function node a.js, The console output is as follows :
a {
}
b {
id: '001' }
No report error , The normal operation . This is because of the reasons mentioned above : If a module is loaded circularly , Output only the executed part , Unexecuted will not output .
A brief analysis of :
- function
node a.js. First go toamodular ,aThe module is imported at the beginningbmodular , Then it will be executed firstb.js, Then returnb.jsDerivedexportsThe object is toaConstant in moduleb. - perform
b.js. At the beginning, I importeda.js. howevera.jsNot completed , Only the executed part will be returned . becausea.jsExported isname、age, herea.jsOnly execute until1That's ok , So actually import at this timea.js, Only empty objects will be returned , becausename、ageNot yet implemented to . thereforerequire('./a')Return empty object , Assign to constanta, So print it out An empty object . - So let's continue
b.js, Finish executing the rest of the code , Normal exportexportsobject , Which includesidattribute . - After execution , Back to the
a.jsIn the first line of ,require('./b')returnbDerivedexportsobject , Containsidattribute . therefore , The following can be printed normally{ id: '001' }. - And then
a.jsin , Finish executing the remaining code .
Thinking questions
Yes a.js、b.js、c.js Three files , perform node a.js, What will the console output ?
// a.js
const b = require('./b');
console.log(exports.x);
exports.x = 'x';
require('./c');
// b.js
const a = require('./a');
console.log(a);
a.x = 'y';
// c.js
const a = require('./a');
console.log(a.x);
answer :
{
}
y
x
The above is what I learned , If there is something wrong , Welcome the criticism that !
边栏推荐
- 【我可以做你的第一个项目吗?】GZIP的细节简介和模拟实现
- 直播课堂系统01-数据库表设计
- 正则表达式常用语法解析
- 【软件测试】如何梳理你测试的业务
- 【测试平台开发】十七、接口编辑页面实现下拉级联选择,绑定接口所属模块...
- Official wechat product! Applet automation framework minium sharing Preview
- 云呐|公司固定资产如何管理?公司固定资产如何管理比较好?
- PKI体系快速介绍
- Canvas from getting started to persuading friends to give up (graphic version)
- R语言实战应用案例:绘图篇(三)-多种组合图型绘制
猜你喜欢

AI acceleration gesture recognition experience based on efr32mg24

【无标题】

Right click to create a new TXT. The new text file is missing. You can solve it by adding a registry. Find the ultimate solution that can't be solved

直播课堂系统01-数据库表设计

C语言项目实战:24点游戏计算器(基于结构体、指针、函数、数组、循环等知识点)

mysql唯一索引无重复值报错重复

R language practical application case: drawing part (III) - drawing of multiple combination patterns

The win11 installation system prompts that VirtualBox is incompatible and needs to uninstall the solution of virtual, but the uninstall list cannot find the solution of virtual

Towhee weekly model

Qt文档阅读笔记-Audio Example解析
随机推荐
Authing supports Zadig! Unified authentication and rapid docking of cloud native users
Introduction and mechanism of Aptos
Authing 支持 Zadig 啦!云原生用户统一认证快速对接
转自玉溪信息公开:mRNA新冠疫苗、九洲马破伤风免疫球蛋白等产品有望年内上市。
452. 用最少数量的箭引爆气球
[record of question brushing] 19. Delete the penultimate node of the linked list
R语言实战应用案例:绘图篇(三)-多种组合图型绘制
Yunna - how to strengthen fixed asset management? How to strengthen the management of fixed assets?
C language introduction practice (11): enter a group of positive integers and sum the numbers in reverse order
【WinForm】关于截图识别数字并计算的桌面程序实现方案
[test platform development] 23. interface assertion function - save interface assertion and edit echo
俄方希望有效落实农产品外运“一揽子”协议
运维高级作业02
[applet automation minium] i. framework introduction and environment construction
Right click to create a new TXT. The new text file is missing. You can solve it by adding a registry. Find the ultimate solution that can't be solved
关于flex布局justify-content:space-around最后一个不对齐的解决方法和为什么这样子解决是讨论
基于nextcloud构建个人网盘
工作小记:一次抓包
Typora图床配置详细教程
直播课堂系统01-数据库表设计