ES6 中的导包

12.导包

ES6 导包语法,主要依赖于exportimport关键字实现。

<script type="module">
// 在平常的 html 文件中需要将 type 中的类型设置为 module
</script>

12.1 按需加载加载

<script type="module">
    // 语法:import 导入的值{解构赋值} from '路径信息'
    import { data, name, age } from './index.js'
    console.log(data, name, age);
</script>
// index.js
export const name = "aaa";
export const age = 12;
export let data = {
    "aa": 11,
    "bb": 22
}

image-20220806023324076

12.2 整体加载

import * as obj from './index.js'
console.log(obj);

image-20220806023748369

12.3 导出函数

// index.js
export const name = "aaa";
export const age = 12;
export let data = {
    "aa": 11,
    "bb": 22
}
export function sayName() {
    return 'My Name is ...'
} // 平常写法

function sayAge() {
    return '马上就要凌晨三点了'
}
export { sayAge }// 将函数封装在对象内部
// 整体加载
import * as obj from './index.js'
console.log(obj);
console.log(obj.sayName());
console.log(obj.sayAge());

image-20220806024823100

12.4 默认值

// index.js
// 设置默认值
const obj = {
    foo: 'foo'
}
// 一个js 文件中 export default 只能写一次该命令。
export default obj;

image-20220806025650333

默认值也可以是一个类

image-20220806030114175

在前端框架中,导包是非常非常重要的。

继续努力,终成大器!

posted @ 2022-08-06 15:18  紫青宝剑  阅读(110)  评论(0编辑  收藏  举报