Modularity of ES6
concept
In the previous JavaScript, there was no concept of modularity. If you want to perform modular operations, you need to introduce a third-party class library. With the development of technology, the front-end and back-end are separated, and the front-end business becomes more and more complicated. It was not until ES6 brought modularity that javascript supported modules for the first time. ES6's modularity is divided into two modules: export and import.
Introduction
1. Export module and import module
In ES6, each module is a file. The variables, functions, and objects defined in the file cannot be obtained from the outside. If you want the content of the module to be read externally, you must use export to expose it (output). Let's first look at an example to modularize a variable. Let's first create a module4.js file to output this variable:
导出模块
export let str1 = "ECMAScript6";
引入模块
import { str1 } from "./module1";
console.log(str1);
Export multiple variables in the module, which can be packaged into object form
let arr = ["ECMAScript", true, "Loki"];
let boo = true;
let first = "first";
export { arr, boo, first };//包装成对象并导出
Introduce modules and receive multiple variables
import { arr, boo, first, str1 } from "./module4";
console.log(str1);
console.log(arr);
console.log(first);
console.log(boo);
2. If you don't want to expose the variable name in the module, you can do it through as**
let myName = "Decepticon";
let myAge = 100;
let sex = "male";
let boo = true;
let fun = function() {
return `我的名字是${myName} ,我的年龄是${myAge},我的性别是${sex} `;
};
fun();
export { myName as name, myAge as age, boo as boo1 };
import { age, boo1, name } from "./module4";
console.log(name);
console.log(age);
console.log(boo1);
3. Import the entire module together
import * as data from "./module4";
console.log(data.age);
console.log(data.name);
console.log(data.boo1);
4. Default export
A module can only have one default export. For the default export, the imported name can be inconsistent with the exported name.
You can put all the variables that need to be exported into an object, and then export through default export
全部导出
export default {
myName: "Loki",
myAge: 20,
sex: "female",
fun: function() {
console.log(this.myAge);
},
};
全部引入
import module4 from "./module4";
console.log(module4.myAge);
console.log(module4.myName);
5. Deal with browsers not recognizing export and import syntax
Use the babel conversion tool to convert ES6 to ES5