当我导航到嵌套路由时使用React.js的懒加载,主包未能加载。

12
我正在使用React Router与组件懒加载,并使用Webpack作为打包工具。当我访问主页“/”时,可以在网络标签中看到bundle.js已加载。当我点击侧边栏中的特定项时,相应的组件也会成功地加载其文件名,例如0.bundle.js。但是,当我直接从搜索栏导航到嵌套路由(例如http://127.0.0.1:8080/forms/select)时,我会遇到以下错误:
GET http://127.0.0.1:8080/forms/bundle.js net::ERR_ABORTED 404 (Not Found)
这个错误表明bundle.js未加载,这意味着它无法加载其他模块。 webpack.config.js
const webpack = require('webpack');
module.exports = {
    entry: './src/index.js',
    module: {
        rules: [],
    },
    resolve: {
        extensions: ['*', '.js', '.jsx'],
    },
    output: {
        path: __dirname + '/dist',
        publicPath: '/',
        filename: 'bundle.js',
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: './dist',
        hot: true,
        historyApiFallback: true,
        
    },
};

.babelrc

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": ["@babel/plugin-syntax-dynamic-import"]
}

routes.js

import { lazy } from 'react';

const Forms = lazy(() => import('../components/uiViews/Forms'));
const SelectForm = lazy(() => import('../components/uiViews/Forms/SelectForm'));
const FormValidation = lazy(() => import('../components/uiViews/Forms/FormValidation'));

const routes = [

    {
        icon: 'form',
        label: 'forms',
        path: '/forms',
        component: Forms,
        children: [
            {
                icon: 'select',
                label: 'selectInput',
                path: '/forms/select',
                component: SelectForm,
            },
            { icon: 'issues-close', label: 'formValidation', path: '/forms/validation', component: FormValidation },
            {
                icon: 'form',
                label: 'wizardForm',
                path: '/forms/wizard',
                component: WizardForm,
            }],
    },
    

];

export default routes;
路由渲染
<Suspense fallback={<div className="spin-loading">  <Spin size="large" /></div>}>
                {routes.map((route, i) => {
                    return route.component ? RouteWithSubRoutes( {...route},`r${i}`) : null;
                })}
</Suspense>

....


function RouteWithSubRoutes(route,key) {
    return route.children ? (
        route.children.map((subRoute,j) => {
            return RouteWithSubRoutes(subRoute,`sr${j}`);
        })
    ) : (
        <Route key={key}  path={route.path} exact component={() =>route.component? <route.component />:<ComingSoon/>} />
    );
}

1
这与React Router无关,因为它不会路由您的资源。我已经有一段时间没有设置webpack了,但我相当确定问题在于publicPathentry和/或output路径之间的相互作用,需要在其中加入一个或两个path.resolve() - Ryan Florence
1个回答

10

试用了几天不同的解决方案后,我终于找到了这个解决方法,它救了我的一天:

... 我最终弄清楚了实际问题,它与Webpack或React Hot Loader或React Router或任何其他库都没有直接关联,至少目前对我来说是如此。当使用HTML5推送状态来操作浏览器历史记录时,我们必须在html头部提供标签。在我的HTML头部提供后,即使在嵌套路由中,HMR也可以完美地工作。

<!DOCTYPE html>
<html>
    <head>
        <base href="/" /> <!-- THIS TINY LITTLE THING -->
        <meta charset="UTF-8" />
        <title>Hello React!</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="/main.bundle.js"></script>
    </body>
</html>



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接