ES6:Module
一、export和import
lib.js
let title = 'ES6 module export';
function sum(a, b) {
return a + b;
}
// 导出tittle、sum
export {
title,
// 还可以设置别名
// title as str,
sum
}
// 下面这些写法也是允许的
// export let title = 'ES6 module export';
// export function sum(a, b) {
// return a + b;
// }
main.js
import {title, sum} from './lib.js'
console.log(title);
console.log(sum(1, 2));
// 导入设置别名
// import {title as strTitle, sum} from './lib.js'
// 导入成对象,将所有的变量和方法挂载到导出对象上
// import * as demo from './lib.js'
// 导入全部对象
//import * from './lib.js'
// 导入成对象,将所有的变量和方法挂载到导出对象上
// import * as demo from './lib.js'
//
// console.log(demo.title);
// console.log(demo.sum(1, 2));
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<!--
浏览器脚本默认使用的语言是JavaScript,因此type="application/javascript"可以省略
使用ES6模块时需要省略号type="module",告诉浏览器这是一个ES6模块
-->
<script type="module" src="main.js"></script>
</body>
</html>
控制台结果:
ES6 module export
3
二、export default和import
lib.js
// 函数导出(第一种)
// export default function Demo() {
// console.log('ES6 module export default');
// }
// 函数导出(第二种)
function Demo() {
console.log('ES6 module export default');
}
export default Demo;
// 变量导出
// let title = 'ES6 module export default';
// export default title;
// 错误的变量导出
// export default let title = 'ES6 module export default';
main.js
import Demo from './lib.js'
// 命名
// 1.直接可以自定义,因为只导出一个变量或方法,不需要匹配
// import Method from './lib.js'
// 2.也可以设置导出别名,导出变量默认为default
// import {default as DemoMethod} from './lib.js'
Demo();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<!--
浏览器脚本默认使用的语言是JavaScript,因此type="application/javascript"可以省略
使用ES6模块时需要省略号type="module",告诉浏览器这是一个ES6模块
-->
<script type="module" src="main.js"></script>
</body>
</html>
控制台输出:
ES6 module export default
三、继承
parent.js
function sum(a, b) {
return a + b;
}
export {
sum
};
child.js
// 将parent.js也全部导出实现继承效果
// 这样import child.js也就同时拥有child.js和parent.js的所有导出字段和方法
export * from './parent.js'
export var a = 1;
export var b = 2;
main.js
import * as math from './child.js';
// math.sum来自parent.js
// math.a和math.b来自child.js
console.log(math.sum(math.a, math.b));
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<!--
浏览器脚本默认使用的语言是JavaScript,因此type="application/javascript"可以省略
使用ES6模块时需要省略号type="moduleinherit",告诉浏览器这是一个ES6模块
-->
<script type="module" src="main.js"></script>
</body>
</html>
控制台输出:
3
四、注意
(一)ES6 模块自动采用严格模式,不论你是否使用下面
"use strict";
(二)导出的值修改权限
- 导出的值如果是变量和方法只读
- 导出的如果是对象,别名是const修饰,对象里面的字段和方法可以修改