export和import的书写方式
一、导出模块(export)
1. 命名导出(Named Exports)
// math.js export const PI = 3.14159; // 导出单个常量 export function sum(a, b) { return a + b; } // 导出单个函数 export class Calculator { /* ... */ } // 导出单个类// 或集中导出(推荐) const PI = 3.14159; function sum(a, b) { /* ... */ } class Calculator { /* ... */ }export { PI, sum, Calculator }; // 统一导出多个成员
2. 默认导出(Default Export)
// config.js const API_KEY = '123-xyz'; export default API_KEY; // 默认导出一个值// 或导出匿名函数/类 export default function(a, b) { return a + b; } export default class { /* ... */ }
3. 混合导出
// utils.js export const VERSION = '1.0'; // 命名导出 export default function log(msg) { // 默认导出console.log(msg); }
二、导入模块(import)
1. 导入命名导出
// 按名称导入(推荐明确导入) import { PI, sum } from './math.js'; // 导入指定成员 console.log(PI); // 3.14159// 别名解决命名冲突 import { sum as add } from './math.js'; // 重命名为 add// 整体导入命名空间 import * as MathUtils from './math.js'; // 全部导入为对象 console.log(MathUtils.PI); // 3.14159
2. 导入默认导出
// 直接导入默认值(无需大括号) import API_KEY from './config.js'; // 默认导出的变量 import logger from './utils.js'; // 默认导出的函数// 同时导入默认和命名 import API_KEY, { VERSION } from './utils.js';
3. 动态导入(按需加载)
// 异步加载模块(返回Promise) const module = await import('./math.js'); console.log(module.PI); // 3.14159
三、特殊场景与技巧
1. 重新导出(Re-export)
// index.js(聚合多个模块) export { PI } from './math.js'; // 重新导出命名成员 export { default as Logger } from './utils.js'; // 重新导出默认成员
2. 空导入(仅执行模块)
// 加载模块但不导入任何内容(用于初始化) import './init.js'; // 执行模块代码
3. 循环依赖处理
// a.js import { bFunc } from './b.js'; export function aFunc() { bFunc(); }// b.js import { aFunc } from './a.js'; export function bFunc() { aFunc(); }
四、代码示例
模块拆分示例:
// 📁 src/ // ├── utils/ // │ ├── math.js (命名导出) // │ └── logger.js (默认导出) // └── app.js (主文件)// math.js export const PI = 3.14159; export function circleArea(r) { return PI * r ** 2; }// logger.js export default function (msg) { console.log(`[LOG] ${msg}`); }// app.js import { PI, circleArea } from './utils/math.js'; import log from './utils/logger.js';log(`Area: ${circleArea(5)}`); // [LOG] Area: 78.53975
五、注意事项
-
文件扩展名
浏览器中需明确写.js
,Node.js 中可省略(需配置"type": "module"
)。 -
路径规则
-
相对路径:
./
或../
-
绝对路径:
/src/utils/math.js
-
第三方模块:
import _ from 'lodash';
-
-
模块作用域
每个模块拥有独立作用域,var
声明的变量不会污染全局。 -
兼容性
浏览器需设置<script type="module">
,旧环境需通过 Webpack/Rollup 打包。
六、最佳实践
-
优先命名导出:明确导出内容,便于代码维护和 Tree Shaking 优化。
-
默认导出的场景:适用于模块主要功能单一(如 React 组件、工具类)。
-
路径别名:通过构建工具配置
@/utils/math
简化长路径。
通过合理使用 export
和 import
,可显著提升代码的可维护性和复用性。