JavaScript 的模块化机制学习

模块导入和导出是 JavaScript 模块化的核心概念。现代 JavaScript 通常使用 ES6(ECMAScript 2015)引入的模块系统,允许使用 import 和 export 语句。

通过范例学习

现在有一个math.js文件

// math.js

// 命名导出多个变量和函数
export const pi = 3.14;

export function add(x, y) {
    return x + y;
}

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

导入命名导出: ${ }

// app.js

// 导入命名导出
import { pi, add, subtract } from './math.js';

console.log(`PI: ${pi}`); // 输出: PI: 3.14
console.log(`3 + 5 = ${add(3, 5)}`); // 输出: 3 + 5 = 8
console.log(`7 - 2 = ${subtract(7, 2)}`); // 输出: 7 - 2 = 5

如果此时还有一个square.js文件需要导入

// square.js

// 默认导出一个函数
export default function square(x) {
    return x * x;
}

同时导入命名和默认导出

app.js

// app.js

import square, { pi, add, subtract } from './math.js';

console.log(`PI: ${pi}`); // 输出: PI: 3.14
console.log(`3 + 5 = ${add(3, 5)}`); // 输出: 3 + 5 = 8
console.log(`Square of 5: ${square(5)}`); // 输出: Square of 5: 25

重命名的导入方式

// app.js

import { add as addition, subtract as subtraction } from './math.js';

console.log(`3 + 5 = ${addition(3, 5)}`); // 输出: 3 + 5 = 8
console.log(`7 - 2 = ${subtraction(7, 2)}`); // 输出: 7 - 2 = 5

聚合模块导入

建一个index,js文件

// index.js

export { pi, add, subtract } from './math.js';
export { default as square } from './square.js';

然后就可以在app.js当中这么用:

// app.js

import { pi, add, square } from './index.js';

console.log(`PI: ${pi}`); // 输出: PI: 3.14
console.log(`3 + 5 = ${add(3, 5)}`); // 输出: 3 + 5 = 8
console.log(`Square of 5: ${square(5)}`); // 输出: Square of 5: 25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值