es6 import export模块化
更新:
在es6之前的一些模块化方案如Commonjs,AMD,CMD,以及循环加载的介绍见我的掘金文章: https:// juejin.im/post/5ed37cc7 e51d45786e496762 ,有兴趣的可以去阅读和关注。
在es6 之前,js模块加载主要采用commonjs 和 AMD规范,前者用于服务器,后者用于浏览器,例如:
let {stat, exists, readFile} = require('fs');
此种方法为运行时加载,实质上时整体加载fs模块,然后在使用时用到三个方法。
es6的模块设计能够完全取代之前的commonjs和AMD规范,成为浏览器和服务器通用的模块解决方案。
import {stat, exists, readFile} from 'fs';
此种方法为编译时加载,实质是从fs模块加载3个方法,而其他方法不加载,es6能够在编译时就能够完成模块编译,因此效率要比commonJS模块的加载方式高。
- export命令
写法1: 定义时输出
export var name = "huangxiaoyu";
export var year = 1995;
写法2: 先定义,后输出
var name = "huangxiaoyu";
var year = 1995;
export {name, year};
上面两种写法其实是等价的。
此外,还可使用as关键字对变量、方法进行重命名(不重命名则默认为原本的文字)
let name1 = "huangcongcong";
let name2 = "huangxiaoyu";
export {
name1 as name,
name2 as nickName
}
2. import 命令
import {name, year} from './profile';
//使用大括号包括住所要引入的变量
import {foo} from "my_module" ;
import {name1 as name} from './profile'; // 使用as 为变量重命名
import 'lodash'; //执行lodash模块,不输入任何值
import * as circle from "./circle"; //使用* 来引入模块下所有的内容
console.log(circle.area(4));
console.log(circel.circumference(14));
3. export default 命令
// default.js
export default function () {
} // 导出默认的匿名函数
import fun1 from './default.js'; // 引入时可以为该匿名函数重新命名,注意此处没有使用大括号
// 也可以导出非匿名函数 foo.js
function foo(){