React Routing with Express, Webpack dev middleware, React router dom

Posted

技术标签:

【中文标题】React Routing with Express, Webpack dev middleware, React router dom【英文标题】: 【发布时间】:2021-08-07 08:17:44 【问题描述】:

我在使用 react-router-dom 和使用 express、webpack-dev-middleware、webpack-hot-middleware 的自定义开发服务器进行路由时遇到问题。

这是我的 webpack 配置。

const path = require("path");
const htmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require('webpack');

module.exports = 
    entry: [
        // 'react-hot-loader/patch',
        'webpack-hot-middleware/client?reload=true',
        './index.js'
    ],
    output: 
        filename: '[name].js',
        path: path.join(__dirname, './dist'),
        publicPath: '/',
        clean: true,
        chunkFilename: '[name].chunk.js',
    ,
    mode: 'development',
    devtool: 'inline-source-map',
    module: 
        rules: [
            
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            ,
            
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            ,
            
                test: /\.s[ac]ss$/,
                exclude: /node_modules/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            ,
            
                test: /\.(png|jpe?g|gif)$/,
                type: 'asset/resource'
            ,
        ]
    ,
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new HtmlWebpackPlugin(
            template: path.join(__dirname, "public", "index.html"),
            title: 'Title'
        ),
    ],
    optimization: 
        splitChunks: 
            chunks: 'all',
        ,
    ,

这是我自定义的 dev express server.js 文件

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const path = require('path');
const fs = require('fs');
const app = express();
const config = require("./webpack.dev.config");

const compiler = webpack(config);

//Enable "webpack-dev-middleware"
app.use(webpackDevMiddleware(compiler, 
    publicPath: config.output.publicPath,
    stats: 
        chunks: false,
        hash: false,
        modules: false,
        version: false,
        assets: false,
        entrypoints: false,
        builtAt: false,
    
));

//Enable "webpack-hot-middleware"
app.use(webpackHotMiddleware(compiler));

app.use(express.static('./public'));


// serve the routes
app.get('*', (req, res) => 
     fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => 
        if (err) 
            res.sendStatus(404);
         else 
            res.send(file.toString());
        
    );
);

app.listen(8000, () => console.log('server listening on port 8000\n'))

当我打开应用程序并且所有路由都给出 404 未找到。但是当我将 writeToDisk 选项添加到编译器选项时,一切正常。我希望路由在不写入磁盘的情况下工作。任何帮助表示赞赏。提前致谢!!

这是我的文件夹结构

【问题讨论】:

您的index.html 来自哪里?看起来您依赖 Webpack 生成或复制到 public 文件夹?如果是这样,那么您肯定需要writeToDisk。如果您尝试从磁盘读取它,请确保它存在(这就是您在 fs.readFile(path.join(compiler.outputPath, 'index.html') 中所做的) 是的,我在公共文件夹中有 index.html 文件,我将它用作 Htmlwebapckplugin 的模板。但是插件会创建一个新的 index.html 文件,对吗?这就是文档中的内容。有什么办法可以把它放在某个地方或者我应该使用什么配置,这样我就不需要将它写入磁盘。 解决方案似乎在这里:github.com/webpack/webpack-dev-middleware/issues/… 另外,官方文档建议使用outputFileSystem.readFile*:github.com/webpack/webpack-dev-middleware#server-side-rendering @Domi 非常感谢 app.use(instance) 两次为我工作,你能告诉我我的配置是否适用于 redux 以及开发。 【参考方案1】:

此问题的解决方案已发布在 Github 问题页面 here。

为了使用webpack-middleware从内存中提供文件,而不将它们写入磁盘,同时还能够明确引用文件(例如在res.render中),建议的解决方案是添加webpackMiddleware两次,在historyApiFallback之前和之后,像这样:

var webpackMiddleware = require("webpack-dev-middleware");
var historyApiFallback = require("connect-history-api-fallback");
var instance = webpackMiddleware(...);
app.use(instance);
app.use(historyApiFallback());
app.use(instance);

【讨论】:

以上是关于React Routing with Express, Webpack dev middleware, React router dom的主要内容,如果未能解决你的问题,请参考以下文章

[PReact] Handle Simple Routing with preact-router

Multipath routing with Group table

Multipath routing with Group table

论文笔记Matrix Capsule with EM Routing

React-Leaflet/React-Routing-Machine:删除路线和航路点

Building Microservices with Spring Cloud - Intelligent Routing