我正在使用 React.lazy 在运行时加载一些 React 类,以便它们不会一次全部加载。我的代码适用于生产,但在我处于开发模式时崩溃。(更新:我的代码不再在生产中工作 - 见下文)。
特定的错误消息非常神秘,因此很难确切知道问题是什么:
Uncaught TypeError: Cannot read property 'call' of undefined at __webpack_require__ (main.js:64)
The above error occurred in one of your React components:
in Unknown
in Suspense
in div (created by Main)
in Main (created by Route)
in Route (created by App)
in Switch (created by App)
in div (created by App)
in Router (created by BrowserRouter)
in BrowserRouter (created by App)
in App
Consider adding an error boundary to your tree to customize error handling behavior.
Uncaught (in promise) TypeError: Cannot read property 'call' of undefined at __webpack_require__ (main.js:64)
第 64 行给出了以下代码:
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
我还有其他没有任何问题的 React 类。
我创建的特定类文件称为 Categories.js。据我所知,我加载的类与任何正在运行的类没有任何不同。我什至尝试重命名类/文件,并且我还删除了我的大部分数据,以防文件中的某些内容导致问题。
以下是我的代码中的相关行:
import React, {Suspense} from 'react';
....
const Categories = React.lazy(()=> import('./Categories'))
....
return (
<Suspense fallback={<div>Loading...</div>}>
<Categories class_select={class_select} />
</Suspense>
)
如果有帮助,这里是我的 webpack.config.js 文件:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = (env, argv) => {
const isProduction = (argv.mode === "production")
return {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
plugins: [
"@babel/plugin-syntax-dynamic-import"
]
}
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
}
]
},
...(isProduction && {
optimization: {
// minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
extractComments: 'all',
compress: {
drop_console: true
},
}
})
],
}
}),
devtool: !isProduction && 'eval-source-map',
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new CopyPlugin([
{ from: 'src/css', to: 'css' }
])
]
};
};
问题
1)是什么导致了这个错误?2)为什么它只在开发模式下而不是生产模式下引起?
更新
我的代码也不再在生产中工作。我收到以下错误:
Uncaught (in promise) TypeError: Cannot read property 'call' of undefined at o (main.js:2).
事实上,它在生产中比开发更糟糕。在生产中,没有一个 React 惰性类在工作。在开发中,只有其中一个不起作用。