Appearance
十四、模块化 import / export(现代开发必备)
模块化是 ES6 引入的重要特性,它允许我们将代码分割成多个文件,提高代码的可维护性和可复用性。
模块化是什么?
模块化是一种将代码分割成独立、可复用单元的方法。每个模块都有自己的作用域,避免了全局变量污染,同时使代码结构更加清晰。
export 导出
1. 命名导出
可以导出多个变量、函数或类:
javascript
// math.js
// 导出变量
export const PI = 3.14159;
// 导出函数
export function add(a, b) {
return a + b;
}
// 导出类
export class Calculator {
multiply(a, b) {
return a * b;
}
}2. 默认导出
每个模块只能有一个默认导出:
javascript
// utils.js
// 默认导出函数
export default function greet(name) {
return `Hello, ${name}!`;
}
// 或者默认导出对象
export default {
add: (a, b) => a + b,
subtract: (a, b) => a - b
};
// 或者默认导出类
export default class Person {
constructor(name) {
this.name = name;
}
}import 导入
1. 导入命名导出
javascript
// 导入多个命名导出
import { PI, add, Calculator } from './math.js';
console.log(PI); // 3.14159
console.log(add(5, 3)); // 8
const calculator = new Calculator();
console.log(calculator.multiply(5, 3)); // 152. 导入默认导出
javascript
// 导入默认导出
import greet from './utils.js';
console.log(greet('John')); // Hello, John!
// 导入默认导出并改名
import utils from './utils.js';
console.log(utils.add(5, 3)); // 83. 混合导入
javascript
// 同时导入默认导出和命名导出
import utils, { PI } from './math.js';
console.log(PI); // 3.14159
console.log(utils.add(5, 3)); // 8默认导出与按需导出
| 特性 | 默认导出 | 命名导出 |
|---|---|---|
| 数量 | 每个模块只能有一个 | 每个模块可以有多个 |
| 导入方式 | 直接导入,可自定义名称 | 使用大括号导入,必须使用原名 |
| 适用场景 | 模块只导出一个主要功能 | 模块导出多个相关功能 |
重命名导入
可以使用 as 关键字重命名导入的模块:
javascript
// 重命名命名导出
import { add as sum, multiply as product } from './math.js';
console.log(sum(5, 3)); // 8
console.log(product(5, 3)); // 15
// 重命名默认导出
import * as math from './math.js';
console.log(math.PI); // 3.14159
console.log(math.add(5, 3)); // 8实战:多文件拆分代码
1. 创建模块文件
user.js
javascript
export class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
}
getUserInfo() {
return {
id: this.id,
name: this.name,
email: this.email
};
}
}api.js
javascript
export function fetchUsers() {
return new Promise(resolve => {
setTimeout(() => {
resolve([
{ id: 1, name: 'John', email: 'john@example.com' },
{ id: 2, name: 'Jane', email: 'jane@example.com' }
]);
}, 1000);
});
}
export function fetchUserById(id) {
return new Promise(resolve => {
setTimeout(() => {
resolve({ id, name: 'John', email: 'john@example.com' });
}, 500);
});
}app.js
javascript
import { User } from './user.js';
import { fetchUsers, fetchUserById } from './api.js';
// 创建用户实例
const user = new User(1, 'John', 'john@example.com');
console.log(user.getUserInfo());
// 调用 API
fetchUsers().then(users => {
console.log('Users:', users);
});
fetchUserById(1).then(user => {
console.log('User:', user);
});2. 运行模块
在现代浏览器中,可以使用 <script type="module"> 标签来加载模块:
html
<!DOCTYPE html>
<html>
<head>
<title>ES6 Modules</title>
</head>
<body>
<script type="module" src="app.js"></script>
</body>
</html>模块化的优势
- 代码组织:将代码分割成多个文件,结构更清晰
- 作用域隔离:每个模块有自己的作用域,避免全局变量污染
- 代码复用:模块可以被多个其他模块导入使用
- 依赖管理:明确模块之间的依赖关系
- Tree Shaking:打包工具可以移除未使用的代码,减小 bundle 体积
注意事项
- 文件扩展名:在浏览器中,模块文件需要使用
.js扩展名 - 路径:导入路径需要使用相对路径(以
./或../开头) - CORS:模块文件需要通过 HTTP 协议加载,不能直接本地打开
- 默认导出:每个模块只能有一个默认导出
通过本章节的学习,你已经掌握了 ES6 模块化的基本用法。模块化是现代 JavaScript 开发的重要特性,它使代码更加组织化、可维护和可复用。
