当前位置:网站首页>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
边栏推荐
- Bom Dom
- Drools dynamically add, modify, and delete rules
- Win10 system OmniPeek wireless packet capturing network card driver failed to install due to digital signature problem solution
- . Net, C # basic knowledge
- 正确遍历EntryList方法
- Sse/avx instruction set and API of SIMD
- Some sudden program ideas (modular processing)
- bellman-ford AcWing 853. 有边数限制的最短路
- Wechat official account payment prompt MCH_ ID parameter format error
- Docsify deploy IIS
猜你喜欢
线性DP AcWing 899. 编辑距离
Deep copy event bus
深拷貝 事件總線
JDBC 预防sql注入问题与解决方法[PreparedStatement]
哈希表 AcWing 840. 模拟散列表
BOM DOM
Bom Dom
Lekao.com: experience sharing of junior economists and previous candidates in customs clearance
JS8day(滚动事件(scroll家族),offset家族,client家族,轮播图案例(待做))
js1day(输入输出语法,数据类型,数据类型转换,var和let区别)
随机推荐
. Net, C # basic knowledge
高性能纠删码编码
哈希表 AcWing 840. 模拟散列表
JSON serialization and parsing
Redis bloom filter
Simple use of drools decision table
Wechat official account payment prompt MCH_ ID parameter format error
Drools terminates the execution of other rules after executing one rule
Adding database driver to sqoop of cdh6
Deep copy event bus
移动式布局(流式布局)
深拷贝 事件总线
js3day(数组操作,js冒泡排序,函数,调试窗口,作用域及作用域链,匿名函数,对象,Math对象)
绕过ObRegisterCallbacks需要驱动签名方法
VLAN experiment
Lekao: 22 year first-class fire engineer "technical practice" knowledge points
When uploading a file, the server reports an error: iofileuploadexception: processing of multipart / form data request failed There is no space on the device
JDBC 预防sql注入问题与解决方法[PreparedStatement]
Redis sentinel mechanism and configuration
Heap acwing 839 Simulated reactor