export * from 用于批量导出外部模块所有命名导出,不包括 default;若存在同名导出需重命名避免冲突,常与 export default 搭配构建统一入口。

export * from 是 ESModule 中用于批量导出外部模块所有命名导出(named exports)的语法,常用于构建模块入口、统一 API 聚合层或重构时做兼容转发。
基本用法:聚合多个模块的命名导出
假设你有多个工具文件:
utils/math.jsexport const add = (a, b) => a + b; export const multiply = (a, b) => a * b;
utils/string.js
export const capitalize = str => str[0].toUpperCase() + str.slice(1); export const truncate = (str, len) => str.length > len ? str.slice(0, len) + '...' : str;
你可以在 utils/index.js 中用 export * from 一次性聚合它们:
export * from './math.js'; export * from './string.js';
这样,其他模块只需导入 utils/index.js 就能拿到全部命名导出:
import { add, multiply, capitalize, truncate } from './utils/index.js';
注意:不导出 default 和重复名冲突
export * from 只转发命名导出,不会转发 default 导出。如果需要导出 default,必须显式写:
export { default as something } from './module.js';-
export { default } from './module.js';(重导出为 default)
若多个被转发模块导出了同名变量(如都导出 format),会报编译/运行时错误(如 Vite、Webpack 或 Node.js ESM 加载器会提示 “Identifier ‘format’ has already been declared”)。需手动重命名避免冲突:
export { format as formatMath } from './math.js';
export { format as formatDate } from './date.js';
// 而不是 export * from './math.js'; export * from './date.js';
搭配 export default 实现完整入口封装
常见做法是:用 export * 聚合命名导出,再单独导出一个默认对象或类:
// utils/index.js
export * from './math.js';
export * from './string.js';
<p>// 同时提供一个默认导出(比如工具集合对象)
export { default as Utils } from './Utils.js'; // 假设 Utils.js 有 default class
// 或直接导出对象
export default {
add,
multiply,
capitalize,
truncate,
}; // 注意:这里需先 import 这些变量,不能直接在 export default 中用未声明名</p>
更稳妥写法(先解构再导出):
import * as math from './math.js';
import * as string from './string.js';
<p>export { ...math };
export { ...string };</p><p>export default { ...math, ...string };</p>
实际项目中的典型场景
- 包的顶层 index.js:如 lodash-es、zustand 的入口,把各子模块导出统一暴露
-
API 层聚合:将
userApi.js、postApi.js的函数全导出到api/index.js -
类型定义集中导出:在
types/index.ts(TS)中export * from './user'; export * from './post';,JS 中同理(只要 .d.ts 或 JS 模块含命名导出)
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











