基于Vite库模式构建React组件库时遇RollupError报错求助
解决RollupError: [type] is not exported by [file]错误
常见原因及修复方案
1. 修正TypeScript类型导出配置
如果组件库基于TypeScript开发,Rollup默认不会自动处理类型声明的导出逻辑,需做以下检查:
- 打开
tsconfig.json,确保compilerOptions中开启declaration: true和declarationMap: true,这会让TS自动生成.d.ts类型声明文件。 - 确认接口/类型使用
export关键字导出,示例:// 正确的类型导出方式 export interface CardProps { title: string; shadow?: boolean; }
2. 配置Vite打包时处理类型文件
在vite.config.ts中补充TypeScript插件配置,让Rollup能正确识别类型导出:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import typescript from '@rollup/plugin-typescript'; import dts from 'rollup-plugin-dts'; export default defineConfig({ plugins: [react(), typescript({ tsconfig: './tsconfig.json' })], build: { lib: { entry: 'src/index.ts', name: 'MyUIComponentLib', formats: ['es', 'umd'], fileName: (format) => `my-ui-lib.${format}.js`, }, rollupOptions: { external: ['react', 'react-dom'], output: { globals: { react: 'React', 'react-dom': 'ReactDOM', }, }, plugins: [dts()], // 专门处理类型声明的打包 }, }, });
3. 检查导入路径的准确性
确认类型导入的相对路径、文件名大小写完全匹配(Linux/macOS环境下文件名区分大小写),避免因路径错误导致Rollup找不到导出的类型:
// 错误示例:路径拼写或大小写不匹配 import { CardProps } from './card/card.props'; // 正确示例:路径与实际文件完全一致 import { CardProps } from './Card/Card.props';
4. 排除第三方依赖类型的干扰
如果错误涉及第三方库的类型,需确保已安装对应版本的@types/xxx类型包,且依赖包版本与类型包版本兼容。
内容的提问来源于stack exchange,提问作者ComCool
相关产品推荐
相关产品推荐

