当前位置:网站首页>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
边栏推荐
- NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
- FBX import under ue4/ue5 runtime
- Do you know all the interface test interview questions?
- 包管理工具
- Deep copy event bus
- 哈希表 AcWing 841. 字符串哈希
- Redis transaction mechanism implementation process and principle, and use transaction mechanism to prevent inventory oversold
- Shuttle encapsulated AppBar
- Js10day (API phased completion, regular expression introduction, custom attributes, filtering sensitive word cases, registration module verification cases)
- MySQL and PostgreSQL methods to grab slow SQL
猜你喜欢
2.6 using recursion and stack - [tower of Hanoi problem]
Efficiency comparison between ArrayList and LinkedList
There is a hidden danger in CDH: the exchange memory used by the process of this role is XX megabytes. Warning threshold: 200 bytes
染色法判定二分图 AcWing 860. 染色法判定二分图
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
Go learning notes - multithreading
bellman-ford AcWing 853. Shortest path with side limit
Record the range of data that MySQL update will lock
Distributed machine learning framework and high-dimensional real-time recommendation system
js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
随机推荐
Openssh remote enumeration username vulnerability (cve-2018-15473)
OpenCV中cv2.VideoWriter_fourcc()函数和cv2.VideoWriter()函数的结合使用
. Net, C # basic knowledge
[FFH] little bear driver calling process (take calling LED light driver as an example)
线性DP AcWing 897. 最长公共子序列
How to write a pleasing English mathematical paper
Js6day (search, add and delete DOM nodes. Instantiation time, timestamp, timestamp cases, redrawing and reflow)
应用LNK306GN-TL 转换器、非隔离电源
Heap acwing 838 Heap sort
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
When uploading a file, the server reports an error: iofileuploadexception: processing of multipart / form data request failed There is no space on the device
ASP. Net MVC default configuration, if any, jumps to the corresponding program in the specified area
接口测试面试题目,你都会了吗?
Input box assembly of the shutter package
Window10 upgrade encountered a big hole error code: 0xc000000e perfect solution
About wechat enterprise payment to change x509certificate2 read certificate information, publish to the server can not access the solution
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
Record the range of data that MySQL update will lock
Leetcode - < dynamic planning special> Jianzhi offer 19, 49, 60
[ybtoj advanced training guide] similar string [string] [simulation]