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

Vite构建React库遇导入错误:已设默认导出仍提示无默认导出

解决React库(Vite+TS)默认导出导入报错问题

以下是针对你遇到的「模块无默认导出」错误的排查与解决方向:

1. 检查TypeScript配置(tsconfig.json)

确保compilerOptions中的关键配置与项目模块类型匹配:

  • 设置"module": "ESNext",和package.json里的"type": "module"保持一致
  • 开启"esModuleInterop": true,让TypeScript正确处理ES模块的默认导出逻辑
  • 配置"jsx": "react-jsx"(React 17+版本推荐),避免JSX转换依赖全局React
  • 开启"declaration": true,确保生成正确的类型声明文件

示例配置片段:

{
  "compilerOptions": {
    "module": "ESNext",
    "esModuleInterop": true,
    "jsx": "react-jsx",
    "declaration": true,
    "outDir": "./dist",
    "strict": true
  },
  "include": ["src/**/*"]
}

2. 配置Vite库模式

开发React库时,需要在vite.config.ts中明确配置库模式,否则Vite会按普通应用打包,可能导致导出异常:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: './src/mainFile.tsx', // 库的入口文件
      name: 'TestFunction', // UMD模式下的全局变量名
      fileName: (format) => `test-function.${format}.js`
    },
    rollupOptions: {
      // 排除React相关依赖,避免打包进库文件
      external: ['react', 'react-dom'],
      output: {
        // 为外部依赖定义全局变量(UMD模式用)
        globals: {
          react: 'React',
          reactDOM: 'ReactDOM'
        }
      }
    }
  }
});

3. 验证导入路径与扩展名

尝试在示例演示文件中添加完整的文件扩展名,避免路径解析歧义:

import TestFunction from "./mainFile.tsx";

同时确保tsconfig.json的resolve.extensions包含.tsx:

{
  "compilerOptions": {
    // ...其他配置
    "resolve": {
      "extensions": [".tsx", ".ts", ".js", ".jsx"]
    }
  }
}

4. 清除缓存并重启服务

删除Vite的开发缓存目录node_modules/.vite,然后重启Vite开发服务,避免旧的编译缓存导致的异常。

5. 检查编译产物

执行npm run build后,查看dist目录下的编译文件,确认ES模块产物中存在export default TestFunction的语句,验证导出逻辑是否正确生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:16:11