es6 中模块的使用总结

ES6 模块导入导出的方式

export语法:

1. 分别暴露

语法:

// a1.js
// 变量暴露形式
export let abcStr = "string";
// 方法暴露形式
export function abcFun(){
    console.log(123);
}

2. 统一暴露

语法:

// a2.js
let abcStr = "string";
function abcFun(){
    console.log(123);
}
export {abcStr, abcFun}
// or user as change name
export {
    abcStr as newStr,
    abcFun as newFun
}
// 不能直接暴露方法名:
    // export abcFun; 错误
    // export {abcFun}; 正确

3. 默认关键字暴露

语法:

// a3.js
export default {
    abcStr: "string",
    abcFun: function(){
        console.log(123);
    }
}

import语法:

通用暴露形式,正对上面的三种export语法

语法:

// 这种方式通用引入上边的三种导出方式
import * as a1 from 'a1.js'
import * as a2 from 'a2.js'
import * as a3 from 'a3.js'
// 因为explorer导出的是一个对象,所以使用可以通过:
let abcStr = a1.abcStr;
a1.abcFun();

使用结构复制的形式导入

语法:

import {abcStr, abcFun} from 'a1.js';
// 因为上边导入第一个的时候已经使用了abcStr名词所以下边的需要改名 使用as关键字更改名称
import {abcStr as abcStr1, abcFun as abcFun1} from 'a2.js';
// 导入default 语法暴露文件
import {default as abcFun3} from 'a3.js';

直接导入

语法:

// 直接导入default 语法暴露文件,这种方式只能正对 default暴露语法
import abcFun3 from 'a3.js';

浏览器中使用模块语法

新版的chrome浏览器已经支持直接使用ES6模块语法具体使用方式如下:

1. 直接页面script标签中写,需要在script标签添加type="module"属性:

<script type="module">
    import * as a1 from 'a1.js'
    import * as a2 from 'a2.js'
    import * as a3 from 'a3.js'
</script>

1. 引入外部js文件,也需要在script标签添加type="module"属性:

// app.js
import * as a1 from 'a1.js'
import * as a2 from 'a2.js'
import * as a3 from 'a3.js'

<script type="module" src="app.js"></script>
posted @ 2020-07-14 18:18  qwguo  阅读(420)  评论(0编辑  收藏  举报