自学内容网 自学内容网

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

原文地址:https://blog.csdn.net/qq_55018264/article/details/142703705

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!