我目前正在构建一个 React 组件库并将其与 Webpack 4 捆绑在一起。
从构建库的包到将其发布到 npm 注册表,一切都运行良好。
但是,我无法在其他 React 应用程序中导入它的任何组件并在运行时收到此错误消息:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
相关代码如下:
我的组件库中的一个dumb组件:
按钮/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 配置中遗漏了一些东西,或者其中一个属性可能是错误的,但是在阅读了多篇文章和教程之后,我无法确定是哪一个。
最佳答案
您正在将您的库导出为 commonjs
并尝试通过 import/export
语法导入它。您应该将输出更改为
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
libraryTarget: "umd",
library: "my-design-system"
}
关于javascript - 使用 Webpack 4 构建 React 组件库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56970495/