首页 > 解决方案 > react-router v4 browserRouter 不工作

问题描述

我不知道我的代码有什么不同。

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const AsyncChunkNames = require('webpack-async-chunk-names-plugin');
const lunaRocketModulesPath = path.resolve(__dirname, 'luna-rocket');

module.exports = {
    entry: [
        '@babel/polyfill',
        path.join(__dirname,'src/app','app.js')
    ],
    output: {
        path: path.join(__dirname,'build'),
        filename: 'index.bundle.js',
        chunkFilename: '[name].bundle.js',
        publicPath: '/', // 헐랭이.. 이 게 뭐길래...
    },
    mode: process.env.NODE_ENV || 'development',
    resolve: {
        alias: {
            'luna-rocket': lunaRocketModulesPath
        },
        extensions: [
            '.js',
        ],
    },
    devServer: {
        contentBase: path.join(__dirname,'src'),
        disableHostCheck: true,
        historyApiFallback: true
    },
    module: {
        rules: [
            {
                // this is so that we can compile any React,
                // ES6 and above into normal ES5 syntax
                test: /\.(js)$/,
                // we do not want anything from node_modules to be compiled
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            },
            {
                test: /\.(css|scss)$/,
                use: [
                    "style-loader", // creates style nodes from JS strings
                    "css-loader", // translates CSS into CommonJS
                    "sass-loader" // compiles Sass to CSS, using Node Sass by default
                ]
            },
            {
                test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
                loaders: ['file-loader']
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname,'src','index.html'),
            inject: 'body',
        }),
        // new AsyncChunkNames()
    ],
    optimization: {
        splitChunks:{
            cacheGroups: {
                default: false,
                vendors: false,
                vendor: {
                    name: 'vender',
                    chunks: "all",
                    test: "/node_module/",
                    priority: 20
                },
                common: {
                    name: 'common',
                    minChunks: 2,
                    chunks: "all",
                    priority: 10,
                    reuseExistingChunk: true,
                    enforce: true
                }
            }
        }
    }
};

应用程序.js

import React, { Suspense, lazy } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Switch, HashRouter, withRouter, useRouterHistory , Redirect} from 'react-router-dom'
import Home from './Home';
import RocketComponent from './RocketComponent';

const Loading = () => <div>loading...</div>


ReactDOM.render(
    <Router>
                <div className="app">
                    <div className="container">
                        <Suspense fallback={<Loading />}>
                            <Route exact path="/" component={Home} />
                            <Route path="/rocket" component={RocketComponent} />
                        </Suspense>
                    </div>
                </div>
    </Router>,
    document.getElementById('app')
);

RocketComponent.js

import HeaderNew from "./HeaderNew";
import React, {lazy, Suspense} from 'react';
import RocketMenuNew from "./RocketMenuNew";
import {Route, Switch} from "react-router-dom";

function scrollToTop() {
    document.body.scrollTop = 0
}

const menuData = [
    {
        title: "LUXAccordion",
        path: "/rocket/LUXAccordion",
        component: "./Documents/LUXAccordion/AccordionDocument"
    },
    {
        title: "LUXActionBar",
        path: "/rocket/LUXActionBar",
        component: "./Documents/LUXActionBar/ActionBarDocument"
    },
    {
        title: "LUXBadge",
        path: "/rocket/LUXBadge",
        component: "./Documents/LUXBadge/BadgeDocument"
    },
    {
        title: "LUXButton",
        path: "/rocket/LUXButton",
        component: "./Documents/LUXButton/ButtonDocument"
    }
]

function DynamicLoader(props) {
        // console.log("title", `./Documents/${title.title}/${title.title.substring(3)}Document`)
        // const LazyComponent = React.lazy(() => import(`./Documents/${title.title}/${title.title.substring(3)}Document`));

    const LazyComponent = lazy(() => import(`${props.component}`));
    console.log("LazyComponent", LazyComponent)
    return (
            <LazyComponent />
    );
}


class RocketComponent extends React.Component {
    render() {
        console.log("this.props.match.path", this.props.match.path)
        return (
            <div className="documents-new">
                <HeaderNew />
                <RocketMenuNew />
                <Switch>
                    {menuData.map((props, i) => {
                        return <Route path={props.path} render={() => <DynamicLoader component={props.component}/>} key={i}/>
                    })}
                </Switch>
            </div>
        );
    }
}

export default RocketComponent

此代码正在运行。但是 RocketComponent.js 移动到了路由目录。不管用。我不知道为什么??

RocketComponent.js --> 路径:app/router/RocketComponent.js

import HeaderNew from "./../HeaderNew";
import React, {lazy, Suspense} from 'react';
import RocketMenuNew from "./../RocketMenuNew";
import {Route, Switch} from "react-router-dom";

function scrollToTop() {
    document.body.scrollTop = 0
}

const menuData = [
    {
        title: "LUXAccordion",
        path: "/rocket/LUXAccordion",
        component: "./../Documents/LUXAccordion/AccordionDocument"
    },
    {
        title: "LUXActionBar",
        path: "/rocket/LUXActionBar",
        component: "./../Documents/LUXActionBar/ActionBarDocument"
    },
    {
        title: "LUXBadge",
        path: "/rocket/LUXBadge",
        component: "./../Documents/LUXBadge/BadgeDocument"
    },
    {
        title: "LUXButton",
        path: "/rocket/LUXButton",
        component: "./../Documents/LUXButton/ButtonDocument"
    }
]

function DynamicLoader(props) {
    const LazyComponent = lazy(() => import(`${props.component}`));
    return (
            <LazyComponent />
    );
}

class RocketComponent extends React.Component {
    render() {

        return (
            <div className="documents-new">
                <HeaderNew />
                <RocketMenuNew />
                <Switch>
                    {menuData.map((props, i) => {
                        return <Route path={props.path} render={() => <DynamicLoader component={props.component}/>} key={i}/>
                    })}
                </Switch>
            </div>
        );
    }
}

export default RocketComponent

我修改了组件路径,app.js 修改了 RocketComponent 的路径。
但不工作错误是 在此处输入图像描述 为什么不工作,路径是正确的,请帮助我。我的 webpack 是 4,babel 7

标签: reactjswebpack

解决方案


推荐阅读