我目前正在构建一个React组件库,并使用Webpack 4进行打包。
从构建库的捆绑包到在npm注册表上发布,一切都运行良好。
但是,在另一个React应用程序中导入其中任何组件时,我无法在运行时获取以下错误消息:
元素类型无效:预期一个字符串(对于内置组件)或类/函数(对于复合组件),但实际得到的是undefined。您可能忘记从定义该组件的文件中导出组件,或者可能混淆了默认和命名导入。
这里是相关的代码:
来自我的组件库的一个蠢笨组件:
button/index.js
import React from "react";
const Button = () => <button>Foobar</button>;
export { Button };
我的库的主要入口点是index.js
:
import { Button } from "./src/components/Button";
export { Button };
我的Webpack配置文件 webpack.config.js
:
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: "./index.js",
plugins: [new CleanWebpackPlugin()],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
libraryTarget: "commonjs",
library: ""
}
};
在其他应用程序中导入此组件的最后步骤:import { Button } from "my-design-system";
我猜我在Webpack配置中漏掉了一些东西,或者某个属性可能是错误的,但是在阅读了多篇文章和教程之后,我仍然无法确定哪一个。
export { Button };
更改为export Button ;
。 - Yasser Zubairexport default Button
将其导出为默认值,然后使用import Button from 'lib'
导入它,但结果相同。 - Arnaud Christ