我从React收到以下错误,我的页面无法加载:Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
当我在React组件顶部使用import
声明,例如import React from "react"
时,就会发生这种情况。
根据关于堆栈溢出的这个问题,答案是将module.exports = ComponentName
更改为export default ComponentName
,但是在我的情况下,这两段代码都抛出相同的错误。
有人可以帮助我找出导致错误的原因吗?
Register.jsx
import React from "react";
const Register = () => {
return (
<div>registration page</div>
)
}
export default Register
webpack.js
const path = require('path');
module.exports = {
mode: 'production',
context: path.join(__dirname, './'),
entry: './app/app.jsx',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
// loader: 'jsx-loader',
use: {
loader: 'babel-loader',
},
exclude: /node_modules/,
include: path.join(__dirname, 'app'),
},
],
},
};
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
答案 0 :(得分:2)
您可能导入不正确。由于您是默认导出,因此请从以下位置更改导入:
import { Register } from '<some_path>/Register';
收件人:
import Register from '<some_path>/Register';
或CommonJS样式:
const Register = require('<some_path>/Register');
到
const Register = require('<some_path>/Register').default;