当前位置:网站首页>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
边栏推荐
- Introduction to CPU instruction set
- Shuttle encapsulated AppBar
- When uploading a file, the server reports an error: iofileuploadexception: processing of multipart / form data request failed There is no space on the device
- AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning
- js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
- bellman-ford AcWing 853. 有边数限制的最短路
- Floyd AcWing 854. Floyd求最短路
- 软件测试面试题-2022年大厂面试题合集
- Calculate the maximum path sum of binary tree
- Leetcode - Sword finger offer 59 - I, 59 - II
猜你喜欢
spfa AcWing 851. spfa求最短路
Enhance network security of kubernetes with cilium
Docker compose configuration mysql, redis, mongodb
Direct control PTZ PTZ PTZ PTZ camera debugging (c)
In development, why do you find someone who is paid more than you but doesn't write any code?
MySQL and PostgreSQL methods to grab slow SQL
BOM DOM
C#运算符
Redis sentinel mechanism and configuration
Simple use of drools decision table
随机推荐
bellman-ford AcWing 853. 有边数限制的最短路
Js10day (API phased completion, regular expression introduction, custom attributes, filtering sensitive word cases, registration module verification cases)
About the loading of layer web spring layer components, the position of the layer is centered
The second composition template of postgraduate entrance examination English / chart composition, English chart composition is enough
计数类DP AcWing 900. 整数划分
"As a junior college student, I found out how difficult it is to counter attack after graduation."
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
2.6 using recursion and stack - [tower of Hanoi problem]
JDBC 预防sql注入问题与解决方法[PreparedStatement]
包管理工具
架构师必须了解的 5 种最佳软件架构模式
Is the neural network (pinn) with embedded physical knowledge a pit?
JDBC prevent SQL injection problems and solutions [preparedstatement]
[FFH] little bear driver calling process (take calling LED light driver as an example)
上手报告|今天聊聊腾讯目前在用的微服务架构
移动式布局(流式布局)
Calculate the maximum path sum of binary tree
Drools executes the specified rule
js3day(数组操作,js冒泡排序,函数,调试窗口,作用域及作用域链,匿名函数,对象,Math对象)
js5day(事件监听,函数赋值给变量,回调函数,环境对象this,全选反选案例,tab栏案例)