从个人NPM组件库导入组件时出现Element type is invalid错误
React组件库发布NPM后导入组件报错解决方案
问题复现
开发演示组件库测试构建系统,编写的Button组件代码如下:
import React from 'react'; import styled from 'styled-components'; const SCButton = styled.button` color: #fff !important; text-transform: uppercase; text-decoration: none; background: #288a0f; padding: 20px; border-radius: 5px; display: inline-block; border: none; transition: all 0.4s ease 0s; `; export interface Props extends ComponentProps { text: string; } interface ComponentProps { id?: string; } const Button = ({ text = 'Button Text', id }: Props) => { const componentProps: ComponentProps = {}; if (id) { componentProps.id = id; } return <SCButton {...componentProps}>{text}</SCButton>; }; export default Button;
使用webpack打包代码输出到dist文件夹,发布到NPM后安装依赖,导入组件时报错如下:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
项目中的导入代码如下:
import logo from './logo.svg' import './App.css' import Button from 'design-system/dist/Button/Button' function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <Button text="hi" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ) } export default App
已确认组件的导入、导出均使用default语法,排除常规导入导出语法不匹配问题。
根因分析
该问题由组件库webpack打包的模块导出配置错误导致:webpack打包库文件时默认会将ES模块的default导出挂载到输出对象的.default属性上,直接导入时拿到的是完整的模块导出对象{ default: Button },而非组件本身,因此React识别到传入的是对象而非组件类/函数,抛出报错。
解决方案
方案1:修改webpack库导出配置
在webpack配置的output字段中添加library配置,指定将default导出作为库的根导出:
// webpack.config.js module.exports = { // 其他配置保持不变 output: { // 原有输出路径、文件名配置保持不变 library: { type: 'umd', export: 'default' }, globalObject: 'this' } }
方案2:添加CommonJS兼容导出
在组件代码的末尾添加兼容CommonJS模块系统的导出语句:
// Button.tsx 原有代码不变,末尾新增 module.exports = exports.default
验证方法
修改前可先通过以下代码确认根因:
import * as ButtonModule from 'design-system/dist/Button/Button' console.log(ButtonModule) // 如果输出结构为 { default: [Function Button] },即可确认是导出配置问题
内容的提问来源于stack exchange,提问作者Josh Bowden
相关产品推荐
相关产品推荐

