当前位置:网站首页>Modular commonjs es module
Modular commonjs es module
2022-07-02 12:43:00 【There is no water in the sea】
One 、 modularization
1、 When there is no modularity
xiaoming/index.js
// We write it into the function , Functions have their own scopes
// function foo() {
// var name = "why";
// var isFlag = false;
// }
// foo();
// But the above writing still needs to be written foo() Execute it , Self executing functions can replace
var moduleA = (function () {
var name = "chen";
var isFlag = true;
// Return the object , Use variables to receive
return {
name: name,
isFlag: isFlag,
};
})()
xiaoming/chen.js
(function () {
if (moduleA.isFlag) {
console.log(" My name is " + moduleA.name);
}
})()
xiaohong/index.js
(function () {
var name = "chen";
var isFlag = false;
})()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="./xiaohong/index.js"></script>
<script src="./xiaoming/index.js"></script>
<script src="./xiaoming/chen.js"></script>
</body>
</html>
2、CommonJS - module.exports Export mode *

chen.js
const name = "chen123";
const age = 23;
function sum(num1, num2) {
return num1 + num2;
}
// export
// Export scheme : 1、module.exports
// module It's also an object ,exports It's also
module.exports = {
aaa: "aaaa",
bbb: "bbb",
name: name,
age: age,
sum: sum,
// es6 Enhanced writing :
// name, age,sum
};
// Export scheme : 2、exports
main.js
// Objects exported using another module , Then you need to import require, Functions can have different parameters
const chen = require("./chen.js"); //require Followed by the path , This require The function returns an object
const {
aaa, bbb } = require("./chen.js"); // It returns an object , Can structure
console.log(chen.aaa);
console.log(aaa);
console.log(bbb);
console.log(chen.name);
console.log(chen.age);
console.log(chen.sum(20, 30));
3、CommonJS internals
They are the same object , Three references point to the same object

chen.js
const info = {
name: "chen",
age: 23,
foo: function () {
console.log("foo function ~");
},
};
setTimeout(() => {
info.name = ' The son of the chosen '
}, 1000)
module.exports = info;
main.js
const chen = require('./chen.js');
console.log(chen);
setTimeout(() => {
console.log(chen);
}, 2000)
3、exports Export mode
chen.js
const name = "chen123";
const age = 23;
function sum(num1, num2) {
return num1 + num2;
}
// exports This is how it is implemented in the source code
// module.exports = {};
// exports = module.exports;
// The second way to export
exports.age = age;
exports.name = name;
exports.sum = sum;
// The final export must be module.exports
// The following writing method cannot be exported
// exports = {
// name: name,
// age: age,
// };
main.js
const chen = require('./chen.js');
console.log(chen.name);
console.log(chen.age);
console.log(chen.sum);
4、require Find the rules
// Situation 1 : Core module , node modular path
const path = require("path");
path.resolve();
// Situation two : route . If it's a folder , Can use folders /index.js
require("./abc");
// Situation three : It's not a core module or a path
const chen = require("chen"); // Looking for main.js Under the directory node_modules
// console.log(module.paths);
5、 Module loading details

6、CommonJS disadvantages 
Two 、ES Module And principle

1、ES Module Basic use **
** Three imports and three exports **
foo.js
// The second way : export export and Declare separate
const name = "chen123";
const age = 23;
function foo() {
console.log("foo function");
}
// export {} This is not an object ,{} It's grammar .
export {
name,
age,
foo,
// You can't write that : name: name
};
// The third way : The second method is alias when exporting
export {
name as fName,
age as fAge,
foo as Ffoo,
};
main.js
// 1、 Import method 1 : Ordinary import
// import { name, age, foo } from "./foo.js";
// import { fName, fAge, Ffoo } from "./foo.js";
// console.log(name);
// console.log(age);
// 2、 Import mode 2 : names
// import { name as fName, age as fAge, foo as ffoo } from "./foo.js";
// 3、 Import mode 3 : Put all the exported content into one identifier
import * as foo from "./foo.js";
console.log(foo.name);
console.log(foo.age);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- Here will be the current ordinary js, It is not allowed to have import. We have to add type attribute , Explain that this is a module -->
<script src="./main.js" type="module"></script>
</body>
</html>
Be careful :
2、ES Module Use a combination of **
format.js
function timeFormat() {
return "2022-02-10";
}
function priceFormat() {
return "222";
}
export {
timeFormat, priceFormat };
math.js
function add(num1, num2) {
return num1 + num2;
}
function sub(num1, num2) {
return num1 - num2;
}
export {
add, sub };
index.js
// 1、 Export method 1 :
// import { add, sub } from "./math.js";
// import { priceFormat, timeFormat } from "./format.js";
// export {
// add,
// sub,
// priceFormat,
// timeFormat
// }
// 2、 Export mode 2 :
// export { add, sub } from "./math.js";
// export { priceFormat, timeFormat } from "./format.js";
// 2、 Export method 3 :
export * from "./math.js";
export * from "./format.js";
main.js
import {
add, sub, priceFormat, timeFormat } from "./utils/index.js";
const sum = add(1,30)
console.log(sum);
3、ES Module - Default**
foo.js
const name = "chen";
const age = 23;
const foo = "foo value is";
// 1. The default export method is 1 :
// export { name, age, foo as default };
// 2、 The default export method is 2 : common
export default foo;
main.js
// export{} export , The name here must be consistent with the exported ,name,age
// import { name, age } from "./foo.js";
// Import statement : The default export is imported
import chen from './foo.js'
console.log(chen);
// Be careful : The default export can only have one
4、ES Module - import function
foo.js
const name = "chen";
const age = 23;
const foo = "foo value is";
export {
name, age, foo };
main.js
// This is synchronous code , If you don't want to finish parsing , Do not block the following code , It can be used as a function
// import { name, age, foo } from "./foo.js";
// import The function returns a Promise. The whole code is asynchronous , It will not affect the operation of the following code
import('./foo.js').then(res => {
// To get the res, In fact, it's the whole { name, age, foo }
console.log(res, res.age);
})
// console.log(name);
// stay import Before the import , The rest of the code is not going to execute , Quite synchronized code
console.log(" Subsequent code ");
// ES11 New features
// meta The attribute itself is an object ,{url: ' The path of the current module '}
console.log(import.meta);
5、ES Module principle

边栏推荐
- js1day(输入输出语法,数据类型,数据类型转换,var和let区别)
- 线性DP AcWing 902. 最短编辑距离
- CV2 in OpenCV VideoWriter_ Fourcc() function and cv2 Combined use of videowriter() function
- Redis bloom filter
- 应用LNK306GN-TL 转换器、非隔离电源
- 接口测试面试题目,你都会了吗?
- JS6day(DOM结点的查找、增加、删除。实例化时间,时间戳,时间戳的案例,重绘和回流)
- PR 2021 quick start tutorial, learn about the and functions of the timeline panel
- Redis avalanche, penetration, breakdown
- Sse/avx instruction set and API of SIMD
猜你喜欢

Distributed machine learning framework and high-dimensional real-time recommendation system

通过反射执行任意类的任意方法

Anti shake throttle

"As a junior college student, I found out how difficult it is to counter attack after graduation."

Programmers can't find jobs after the age of 35? After reading this article, you may be able to find the answer

深拷贝 事件总线

Drools dynamically add, modify, and delete rules

bellman-ford AcWing 853. 有边数限制的最短路

架构师必须了解的 5 种最佳软件架构模式

JS8day(滚动事件(scroll家族),offset家族,client家族,轮播图案例(待做))
随机推荐
arcgis js 4. Add pictures to x map
bellman-ford AcWing 853. 有边数限制的最短路
计数类DP AcWing 900. 整数划分
ArrayList与LinkedList效率的对比
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
LTC3307AHV 符合EMI标准,降压转换器 QCA7005-AL33 PHY
Shutter encapsulated button
Sweetheart leader: Wang Xinling
JDBC 预防sql注入问题与解决方法[PreparedStatement]
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
JS7day(事件对象,事件流,事件捕获和冒泡,阻止事件流动,事件委托,学生信息表案例)
spfa AcWing 852. SPFA judgement negative ring
深拷贝 事件总线
Heap acwing 838 Heap sort
js1day(输入输出语法,数据类型,数据类型转换,var和let区别)
应用LNK306GN-TL 转换器、非隔离电源
趣味 面试题
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
模块化 CommonJS ES Module