export命令定义模块
下边我们定义一个简单的Module模块(mod.js),一个文件就是一个模块,所有要提供给模块外部脚本调用的对外接口(变量、函数、对象、类等)必须加上export命令,否则外部脚本无法调用:
//export变量
export let name = 'Jack';
//export函数
export function hello(){
console.log('hello,' + name);
}对外接口也可以先声明,再export:
//export变量
let name = 'Jack';
export {name};
//export函数
function hello(){
console.log('hello,' + name);
}
export {hello};还可以在模块文件末尾一起export,更直观:
let name = 'Jack';
function hello(){
console.log('hello,' + name);
}
export {name, hello};注意:export命令可以出现在模块的任何位置,但只能处于模块顶层,如果处于块级作用域内将会报错。export命令后面只能跟声明语句,"export let name"和"let name;export {name}"这两种写法都可以,若写成export name(没有大括号)会报错。
import命令加载模块
定义好模块,我们就可以使用import命令加载模块并使用其提供的接口了,注意import的变量名必须和export的对外接口名称一一对应:
<script type="module">
import {name, hello} from './mod.js';
console.log(name);
hello();
</script>也可以不逐个指定变量名,使用星号(*)将模块所有接口加载进来赋值给一个对象:
<script type="module">
import * as mod from './mod.js';
console.log(mod.name);
mod.hello();
</script>export和import重命名
export对外接口名和import变量名都可以使用as进行重命名:
let name = 'Jack';
function hello(){
console.log('hello,' + name);
}
export {name as n, hello};<script type="module">
import {n, hello as h} from './mod.js';
console.log(n);
h();
</script>export default命令
export default命令用于设置模块的默认对外接口:
let name = 'Jack';
function hello(){
console.log('hello,' + name);
}
export default hello;<script type="module">
import hello from './mod.js';
hello();
</script>注意export default后面的对外接口名称不需要大括号,import后面的变量名可以不和接口名称一样,也就是不需要知道确切的接口名称,用任意变量名都是可以的:
<script type="module">
import todo from './mod.js';
todo();
</script>Module模块嵌套
Module模块可以在一个模块中嵌套另一个模块,例如在mod2.js中嵌套mod.js模块:
import {name, hello} from './mod.js'
export {name, hello}也可以直接export:
export {name, hello} from './mod.js'这种写法省略了import,mod2.js中不能使用mode.js的对外接口,只起到转发作用。
评论(0)
暂无评论。