-
ES模块化的导入和导出
html部分:
<script src="./aaa.js" type="module"></script>
<!-- <script src="./bbb.js" type="module"></script> -->
<script src="./ccc.js" type="module"></script>
模块部分:
let name = "xiaoming"
let age = 12
let flag = true
function sum1(num1, num2) {
return num1 + num2
}
if (flag) {
console.log(sum1(20, 30));
}
class Person1 {
constructor(name, age) {
this.name = name;
this.age = age
}
run() {
console.log(this.name + ' run----------------');
}
}
// 1.导出方式一
export {
flag, sum1, Person1
}
// 2.导出方式二
export let num1 = 1000;
export let height = 1.88;
export function sum2(num1, num2) {
return num1 + num2;
}
export class Person2 {
constructor(name, age) {
this.name = name;
this.age = age
}
run() {
console.log(this.name + ' run----------------');
}
}
// 3.export default
// 某些情况下,一个模块中包含某个功能,我们并不希望给这个功能命名,而是让导入者自己来命名,同一个模块中default只能有一个
// const address = '山东省';
// export default address;
export default function test(){
console.log('export default 导出函数');
}
导出部分:
// 1.导出方式一
import{flag, sum1, Person1} from './aaa.js'
if (flag) {
console.log('小明是天才');
console.log(sum1(10, 20));
let p1 = new Person1('小一', 11);
p1.run()
}
// 2.导出方式二
import {num1, height, sum2, Person2} from './aaa.js';
console.log(num1);
console.log(height);
console.log(sum2(11, 22));
let p = new Person2('小二', 5);
p.run()
// 3.export default
import ttt from './aaa.js' // 导出aaa中默认导出的内容
ttt()
// 全部导入
import * as info from './aaa.js';
console.log(info.sum1(1, 2));
console.log(info.sum2(2, 2));