一、什么是模块化?
1.1. 在ES5中本身是不支持模块化的,后来一些社区的大佬制定了一个模块规范,主要分为两种,一个是用于服务器的CommonJs,比如nodeJS中的require;另一个是用于客户端的AMD,比如requireJs。
1.2. 在ES6中专门提供了通用的模块化方案(export / import)。
二、export和import的使用
2.1. export:用于导出模块,可以导出各种类型的变量。比如:字符串、数值、函数、对象 等等等等。
2.2. import:用于导入模块,模块中的变量经过导入之后就可以在js文件中使用。
导出模块:export { }
导入模块:import { } from ’ 路径 ’
//Demo.js
let str = 'hello';
let method = () =>{
console.log('hello');
}
class Test{
constructor(){
console.log('hello');
}
}
//导出模块
export {str as stra ,method,Test}
//demo.html
//导入模块
<script type='module'>
import {stra,method,Test} from './js/Demo.js';
console.log(stra);// hello
</script>
export { }:导出模块可以把 { } 内部的变量等使用 as关键字起别名,在import导入模块时,也需要导入别名才能正常使用。
注意:在导入模块的时候,from 后面的路径可以是绝对路径也可以是相对路径,还可以是网络路径。在导入模块时,看自身需求,需要哪一项就导入哪一项,没有硬性要求全部导入。
导出模块:export default { }
导入模块:import 别名(对象) from ’ 对象 ’
//demo.js
let str = 'hello';
let method = () =>{
console.log('hello');
}
class Test{
constructor(){
console.log('hello');
}
}
//导出模块
export default {str,method,Test}
//demo.html
//导入模块
import temp from './js/demo.js';
console.log(temp.str);//hello
批量导入:
<script type="module">
//批量导入
import * as temp from './js/Demo.js'
console.log(temp.str);// hello
</script>
import * 相当于全部导入,as temp 给导入的模块起一个别名,使用别名调用模块内的变量等。
export default { } 导出的模块不能使用 import * 导入。