当前位置:网站首页>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

边栏推荐
- Efficiency comparison between ArrayList and LinkedList
- bellman-ford AcWing 853. 有边数限制的最短路
- In development, why do you find someone who is paid more than you but doesn't write any code?
- 通过反射执行任意类的任意方法
- FBX import under ue4/ue5 runtime
- spfa AcWing 851. spfa求最短路
- [I'm a mound pytorch tutorial] learning notes
- Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
- Direct control PTZ PTZ PTZ PTZ camera debugging (c)
- Interview questions for software testing - a collection of interview questions for large factories in 2022
猜你喜欢

Openssh remote enumeration username vulnerability (cve-2018-15473)

C#修饰符

Floyd AcWing 854. Floyd求最短路

模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计

Hash table acwing 840 Simulated hash table

VLAN experiment

哈希表 AcWing 841. 字符串哈希

染色法判定二分图 AcWing 860. 染色法判定二分图

Js8day (rolling event (scroll family), offset family, client family, carousel map case (to be done))

Programmers can't find jobs after the age of 35? After reading this article, you may be able to find the answer
随机推荐
3 A VTT端接 稳压器 NCP51200MNTXG资料
Redis sentinel mechanism and configuration
JSON serialization and parsing
Bom Dom
Shuttle encapsulated AppBar
In development, why do you find someone who is paid more than you but doesn't write any code?
应用LNK306GN-TL 转换器、非隔离电源
This "little routine" is set on the dough cake of instant noodles. No wonder programmers are always hungry
获取文件版权信息
包管理工具
Interview questions for software testing - a collection of interview questions for large factories in 2022
[ybtoj advanced training guide] similar string [string] [simulation]
接口测试面试题目,你都会了吗?
std::vector批量导入快速去重方法
spfa AcWing 852. SPFA judgement negative ring
Deep Copy Event bus
ArrayList与LinkedList效率的对比
The programmer and the female nurse went on a blind date and spent 360. He packed leftovers and was stunned when he received wechat at night
Simple use of drools decision table
Calculate the maximum path sum of binary tree