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

构建React组件库引入Demo项目时遇Invariant Violation错误求助

Fixing "Invariant Violation: Element type is invalid" in React Component Library Imports

Hey there! That error is super common when working with React component libraries, and it almost always boils down to mismatched imports/exports or missing exports entirely. Let's break down the most likely fixes:

1. Check for Default vs. Named Import/Export Mismatch

This is the #1 culprit. If your component uses a default export in the library, you can't import it with curly braces (and vice versa):

  • If your component uses default export:

    // Component library's Button.js
    export default function Button() { /* ... */ }
    

    Then in your Demo project, import it without curly braces:

    import Button from 'your-component-library';
    
  • If your component uses named export:

    // Component library's Button.js
    export function Button() { /* ... */ }
    

    Then import it with curly braces:

    import { Button } from 'your-component-library';
    

2. Verify Your Library's Entry File (index.js) Exports Components

Your library's root index.js needs to explicitly export components so they're accessible to the Demo project. For example:

// Component library's index.js
// Export single component (default)
import Button from './Button';
export default Button;

// OR export multiple components (named)
export { Button } from './Button';
export { Input } from './Input';

If you forget this step, importing from your library will return undefined—exactly the issue you're seeing.

3. Ensure Individual Component Files Export Correctly

Double-check that the component files themselves actually export the component. It's easy to forget this line!

// Component library's Button.js
function Button() {
  return <button>Click Me</button>;
}

// Don't forget this!
export default Button;
// OR
export { Button };

4. Confirm Package Path/Main Entry is Correct

If you're linking the library locally or publishing it, make sure your library's package.json has the correct main field pointing to your entry file. For example:

{
  "main": "dist/index.js" // Or "src/index.js" if you're not building yet
}

A wrong path here means your Demo project can't find the components at all.

Once you've checked these points, the error should disappear. Start with the import/export mismatch—it's the most frequent cause!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:18:21