ES6中import和export的基本使用
相对于ES5,ES6自带模块化思想。在html文件中使用script标签导入js文件时,加上type属性并设置为module。<script src="main.js" type="module"></script>
这个js文件就会成为一个独立的模块。而在这些独立的模块之间复用资源就需要进行导入和导出。
1、export导出
①定义了就直接导出:
// 导出变量
export var name= 'bsy';
export var year = 1958;
// 导出函数
export function mul(num1, num2) {
return num1 + num2;
}
// 导出类
export class Person() {
constructor(name, age){
this.name = name;
this.age = age;
}
say() {
console.log('aaaaaaa...');
}
}
②全部定义好之后,统一导出(推荐写法):
var name= 'bsy';
var year = 1958;
function mul(num1, num2) {
return num1 + num2;
}
export class Person() {
constructor(name, age){
this.name = name;
this.age = age;
}
say() {
console.log('aaaaaaa...');
}
}
// 定义好之后,统一放到对象中进行导出
export {name, year, mul, Person};
③export default(一个模块中只能有一个)
作用: 其他模块进行导入的时候,可以让导入者对这个导入功能自己来命名。(在导入的时候不需要加大括号,详见下方的import导入③)
例子:
// 可以是变量、函数、类等等
export default name;
2、import导入
①使用大括号具体地、一项项地进行导入:
import {name, age, height} from "./main.js";
②将js文件中的全部导入,使用* :
import * as main from "./main.js";
// 使用
console.log(main.name);
console.log(main.height);
③import default(导入export中的default):
// 为该功能进行重命名为fullname
import fullname from "./main.js";
注:使用import和export的前提是,一定要将script标签中的type属性设置为module。<script src="main.js" type="module"></script>