模块化 export 和 import
import 导入模块、export 导出模块
可以直接在任何变量或者函数前面加上一个 export 关键字,就可以将它导出。
在一个文件中:
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
然后在另一个文件中这样引用:
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3));
总结
//mod.js
// 第一种模块导出的书写方式(一个个的导出)
// 导出普通值
export let a = 12;
export let b = 5;
// 导出json
export let json = {
a,
b
};
// 导出函数
export let show = function(){
return 'welcome';
};
// 导出类
export class Person{
constructor(){
this.name = 'jam';
}
showName(){
return this.name;
}
}
//index.js
//导出模块如果用default了,引入的时候直接用,若没有用default,引入的时候可以用{}的形式
// 导入模块的方式
import {
a,
b,
json,
show,
Person
} from './mod.js';
console.log(a); // 12
console.log(b); // 5
console.log(json.a); // 12
console.log(json.b); // 5
console.log(show()); // welcome
console.log(new Person().showName()); // jam
//mod1.js
// 第二种模块导出的书写方式
let a = 12;
let b = 5;
let c = 10;
export {
a,
b,
c as cc // as是别名,使用的时候只能用别名,特别注意下
};
//index1.js
// 导入模块的方式
import {
a,
b,
cc // cc是导出的,as别名
} from './mod1.js';
console.log(a); // 12
console.log(b); // 5
console.log(cc); // 10
//mod2.js
// 第三种模块导出的书写方式 ---> default
// default方式的优点,import无需知道变量名,就可以直接使用,如下
// 每个模块只允许一个默认出口
var name = 'jam';
var age = '28';
export default {
name,
age,
default(){
console.log('welcome to es6 module of default...');
},
getName(){
return 'bb';
},
getAge(){
return 2;
}
};
//index2.js
// 导入模块的方式
import mainAttr from './mod2.js';
var str = ' ';
// 直接调用
console.log(`我的英文名是:${mainAttr.name}我的年龄是${mainAttr.age}`);
mainAttr.default(); // welcome to es6 module of default...
console.log(mainAttr.getName()); // bb
console.log(mainAttr.getAge()); // 2
//mod3.js
var name = 'jam';
var age = '28';
export function getName(){
return name;
};
export function getAge(){
return age;
};
//index3.js
// 导入模块的方式
import * as fn from './mod3.js';
// 直接调用
console.log(fn.getName()); // jam