ES6-模块化规范

ES6-模块化规范

导出

// 1. 模块私有的内容
function multiply (x, y) {
    return x * y;
}


// 2. 模块导出的内容
export function sum (x, y) {
    return x + y;
}

export function substract (x, y) {
    return x - y;
}

// 3. 一次导出多个模块成员
function divide (x, y) {
    return x / y;
}

function remainder (x, y) {
    return x % y;
}

export { divide, remainder };

// 4. 为导出成员重命名
export { divide as div, remainder as rem };


// 5. 默认导出,模块默认导出成员,其他模块导入该成员时,名称不能写到大括号中,并且无需与导出时的名称一致。
export default function max (x, y) {
    return x > y ? x : y;
}


// 6. 每个模块只能有一个默认导出,因此下面的代码会抛出错误。
export default function min (x, y) {
    return x < y ? x : y;
}

导入

// 1. 从 module1.js 中导入 sum() 和 substract() 方法
import { sum, substract } from './13-module1.js';

// 使用从 module1.js 中导入的方法
console.log(sum(12, 48))
console.log(substract(12, 48))

// 2. 导入重命名之后的模块成员
// 注意,必须要写成重命名之后的名称(div,rem),不能写成重命名之前的名称(divide,remainder)
import { div, rem } from './13-module1.js';
console.log(div(48, 12))
console.log(rem(48, 12))

// 3. 导入其他模块默认导出成员
// 注意,名称不能写到大括号中,并且无需与导出时的名称一致。
import abc from './13-module1.js';
console.log(abc(12, 48))

// 4. 同时导入其他模块的默认导出的成员和普通导出的成员
import abc, {sum, div} from './13-module1.js'
console.log(abc(12, 48))
console.log(sum(12, 48))
console.log(div(12, 48))

// 5. 为导入的成员重命名
// 注意,重命名之后不能再使用之前的名称了,否则会抛出错误。
import { substract as sub} from './13-module1.js';
console.log(sub(12, 48))
console.log(substract(12, 48));  // 抛出错误

// 6. 导入其他模块导出的所有成员
import * as module1 from './13-module1.js'
console.log(module1.sum(12, 34))
console.log(module1.default(12, 34))

// 7. 导入没有导出任何成员的模块,目的是想让模块中的代码执行
import './13-module1.js';

// 下面是一个简单的使用场景:

// module1.js 文件中有如下代码:
let age = 20;

export function getAge () {
    return age;
}

export function setAge () {
    age++;
}

// module2.js 文件中的代码如下:
import { setAge } from './13-module1.js';
setAge();

// module3.js 文件中的代码如下:
import './module2.js';
import { getAge } from './module1.js';
console.log(getAge());  // 21

// 8. 将导入的成员重命名之后再次导出
export { divide as div, remainder as rem } from './13-module1.js';
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值