<p>ESModule 中通过逐层 index.js re-export 实现模块聚合,推荐扁平目录按功能划分,每层 index.js 显式命名导出并提供默认对象,根 index.js 按需聚合、避免 export * 和副作用,以保障 Tree-shaking 和依赖清晰。</p>

ESModule 中通过 index.js 聚合多层级模块,核心是“逐层向上 re-export”,不需手动列出所有子模块,关键在于路径清晰、导出一致、避免循环依赖。
目录结构设计要扁平且可预测
推荐按功能或领域划分子目录,每个子目录内保持 index.js 作为该层的统一入口:
-
src/utils/→ 含date.js、string.js、index.js -
src/api/→ 含user.js、product.js、index.js -
src/index.js(根聚合)只 re-export 各顶层目录的index.js
每一层 index.js 都用命名导出 + 默认导出组合
避免只用 export * from './xxx'(会丢失默认导出),推荐显式控制导出内容:
// src/utils/index.js
export { default as formatDate } from './date.js';
export { default as truncate } from './string.js';
export { isEmail, isPhone } from './validators.js';
<p>// 同时支持整体导入:import utils from './utils.js'
export default {
formatDate,
truncate,
isEmail,
isPhone
};根 index.js 按需聚合,不盲目全量导出
根 src/index.js 不应简单 export * from './utils'; export * from './api',而应有明确意图:
立即学习“Java免费学习笔记(深入)”;
- 导出常用工具:
export { formatDate, truncate } from './utils'; - 导出 API 类:
export { UserAPI, ProductAPI } from './api'; - 提供默认对象(可选):
export default { utils: { formatDate }, api: { UserAPI } };
这样使用者能精准导入:import { formatDate } from 'mylib'; 或 import mylib from 'mylib';
注意 Tree-shaking 和循环依赖风险
Webpack / Vite 默认支持 ESM 的静态分析,但以下情况会破坏摇树:
- 在
index.js中执行副作用代码(如调用函数、修改全局) - 跨目录直接相互
import(如utils/index.js导入api/user.js) - 用
export * from且被导出模块本身有默认导出(部分打包器处理不一致)
建议:所有 index.js 只做声明性导出,不执行逻辑;模块间依赖走单向层级(底层 → 上层),勿反向穿透。


















