export和import
介绍:
export和import都是ES6中的语法,是用来导出和导入模块的,一个模块就是一个js文件,他拥有独立的作用于
,里面定义的变量外部是无法获取的。
示例:(将一个配置文件作为模块导出和导入)
//index.js
var Index = {
version:'1.0.0'
};
export {Index};
或:
//index.js
export var Index ={
version:'1.0.0'
};
还可以导出其他类型,比如函数,数组,常量等,拿一个函数为例:
//index.js
export function index(a,b){
return a + b;
};
在模块导出之后,在需要使用模块的文件使用import再导入,就可以在这个文件内使用这些模块了。
//index.js
import {Index} from './index.js';
console.log(Index);//{version:'1.0.0'}
console.log(index(2,5));//7