You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从npm包导入并导出除指定模块外的所有内容?

解决方案

你之前的代码问题在于最后是把rest作为一个对象导出,而不是把rest里的每个组件单独导出,导致用户使用你的packageB时无法直接通过import { Button } from 'packageB'这类方式拿到组件,不符合预期。

下面是两种可行的实现方式:

方法1:解构后逐个导出剩余组件,再导出自定义组件

// 导入MUI所有导出项
import * as muiAllExports from '@mui/material';

// 排除不需要的原生组件,剩余组件存入rest
const { Switch, Grid, ...rest } = muiAllExports;

// 将rest中的所有组件逐个导出
export { ...rest };

// 导出你的自定义Switch和Grid组件
export { default as Switch } from './your-custom-switch';
export { default as Grid } from './your-custom-grid';

方法2:批量导出+覆盖(推荐)

这种方式更简洁,利用ES模块的导出覆盖特性:

// 先导出MUI的所有组件
export * from '@mui/material';

// 用自定义组件覆盖原生的Switch和Grid导出
export { default as Switch } from './your-custom-switch';
export { default as Grid } from './your-custom-grid';

export * from会导入并导出源包的所有导出项,之后导出的同名自定义组件会直接覆盖之前的原生导出,用户使用时可以直接通过import { Switch, Grid, Button } from 'packageB'拿到自定义的Switch、Grid,以及MUI原生的Button等组件。

如果你的自定义组件是命名导出而非默认导出,只需调整最后两行:

export { Switch } from './your-custom-switch';
export { Grid } from './your-custom-grid';

内容的提问来源于stack exchange,提问作者phantomCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:35:50