ES6 模块知识点总结

模块化 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
  • 59
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 52
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 52
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值