[英]Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object in ReactJS
[英]Material UI - Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object
你好嗎?
我有一個帶有 Webpack 和 Babel 的 React 項目,我正在嘗試添加 Material UI ( https://mui.com/ ) 組件,但是,當我將 MUI 組件導入我的項目時,出現下一個錯誤:
元素類型無效:應為字符串(對於內置組件)或類/函數(對於復合組件)但得到:object。
我發現的解決方法是添加“.default”導入,但我不明白為什么我不能以傳統方式導入它。
這是產生錯誤的測試組件代碼:
const React = require("react");
const Button = require("@mui/material/Button");
const Navbar = () => {
return <Button variant="contained">Contained</Button>;
};
module.exports = Navbar;
這是我的.babelrc和webpack.config代碼:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
output: {
path: path.join(__dirname, "/dist"),
filename: "index.bundle.js",
},
devServer: {
port: 8443,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({ template: "./src/index.html" }),
new MiniCssExtractPlugin(),
],
};
有誰知道我做錯了什么? 我知道這可能很愚蠢,但我應該能夠按照 MUI 文檔中所述的“正常”方式導入這些組件,相反,我必須使用“.default”方式導入它們。
在此先感謝,抱歉我的英語不好。
MUI 旨在與 EcmaScript 模塊 (ESM) 一起使用,而不是與 CommonJs (CJS) 一起使用。 如果您確實想使用 CJS,您可以這樣做,但是由於 ESM 和 CJS 不是 100% 兼容的,您將需要一些解決方法。
能夠使用 CJS 語法導入
const Button = require("@mui/material/Button");
MUI 需要導出(使用 CJS)
module.exports = function Button(props) { ... }
但是Button
模塊的整個導出是Button 組件,模塊無法導出任何其他內容。 因此,所有內容都以命名導出方式導出,而組件本身以名稱default
導出。
ESM 導入理解default
,您可以使用縮寫形式,但 CJS 僅導入 javascript object,即{ default: ... }
。
@mui/material/Button/index.js
出口:
export { default } from './Button';
可以使用 CJS 導入:
const Button = require("@mui/material/Button").default;
, 或者const Button = require("@mui/material/Button/index").default;
@mui/material/index.js
出口:
export { default as Button } from './Button';
export * from './Button';
可以使用 CJS 導入:
const Button = require("@mui/material/index").Button;
( export *
只是“Button 的所有內容”,但沒有從 Button 導出任何其他內容,例如getButtonUtilityClass
來自buttonClasses
,但我們對此不感興趣)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.