JavaScript 模块系统允许你将代码分割成多个文件,并通过导出(export)和导入(import)功能在这些文件之间共享功能。这是现代 JavaScript 开发的基础部分。
// math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// app.js
import { PI, add, subtract } from './math.js';
console.log(PI); // 3.14159
console.log(add(5, 3)); // 8
一个模块只能有一个默认导出:
// logger.js
export default function(message) {
console.log(`LOG: ${message}`);
}
// app.js
import log from './logger.js';
log('Hello World'); // LOG: Hello World
可以同时使用命名导出和默认导出:
// utils.js
export default function(config) {
// 默认导出
}
export function helper1() {
// 命名导出
}
export function helper2() {
// 命名导出
}
// app.js
import mainFunction, { helper1, helper2 } from './utils.js';
可以使用 as
关键字重命名导入:
import { add as addNumbers, subtract as subtractNumbers } from './math.js';
可以使用 *
导入所有命名导出:
import * as math from './math.js';
console.log(math.PI);
console.log(math.add(2, 3));
ES2020 引入了动态导入,允许按需加载模块:
async function loadModule() {
const module = await import('./math.js');
console.log(module.add(2, 3));
}
type="module"
属性<script type="module" src="app.js"></script>
模块系统是现代 JavaScript 开发的重要组成部分,它使代码更易于组织、维护和重用。