【问题标题】:How can webpack devServer accept other paths except root / in the browser?webpack devServer如何在浏览器中接受除root/之外的其他路径?
【发布时间】:2020-02-22 20:06:07
【问题描述】:

我遵循https://createapp.dev/ 的 webpack 设置,然后将我的源代码从 create-react-app 设置为 webpack。 但是我有一个热重新加载的问题。当我修改除/之外的页面时,浏览器不能接受除/之外的任何路由器路径。

当我通过 'yarn start' 运行 webpack devserver 时,热重装适用于 '/' 例如:http://localhost:4000。但无法访问其他路径,例如“/main”、“/login”等... 错误消息是例如当我尝试刷新 /main 时,然后我得到“无法获取 /main”。 我试图找到一些资源,比如在 webpack 设置中添加 'inline : true' 并且也添加了 hot。

我也找到其他人的文章,但他们只显示/页面热重载,不像其他页面组件热重载。

我也参考了这个网站。 https://github.com/gaearon/react-hot-loader/issues/1150

// webpack.config.js
const webpack = require('webpack');
const path = require('path');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const config = {
    entry: [ 'react-hot-loader/patch', 'react-hot-loader/babel', './src/index.tsx' ],
    output: {
        publicPath: './dist',
        path: path.resolve(__dirname, 'dist'),
        filename: '[id].bundle.js',
        chunkFilename: '[id].js' // will auto assign a id to your separate chunks
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ],
                exclude: /\.module\.css$/
            },
            {
                test: /\.ts(x)?$/,
                use: [ 'awesome-typescript-loader' ],
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 1,
                            modules: true
                        }
                    }
                ],
                include: /\.module\.css$/
            },
            {
                test: /\.svg$/,
                use: 'file-loader'
            },
            {
                test: /\.png$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            mimetype: 'image/png'
                        }
                    }
                ]
            }
        ]
    },
    resolve: {
        extensions: [ '*', '.js', '.jsx', '.tsx', '.ts', '.css', '.sa' ],
        alias: {
            'react-dom': '@hot-loader/react-dom'
        }
    },
    devServer: {
        port: 4000,
        contentBase: './dist',
        proxy: {
            '/myserver': {
                target: {
                    host: 'localhost',
                    protocol: 'http:',
                    port: 8080
                }
            }
        },
        hot: true
    },
    "devtool": "source-map",
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
        new LodashModuleReplacementPlugin(),
        new HtmlWebpackPlugin({
            template: 'index.html',
            inject: false,
            appMountId: 'app'
        })
    ],
    optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendors',
                    chunks: 'all'
                }
            }
        }
    }
};

module.exports = (env, argv) => {
    if (argv.hot) {
        // Cannot use 'contenthash' when hot reloading is enabled.
        config.output.filename = '[name].[hash].js';
    }

    return config;
};

//index.tsx
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as ReactDOM from 'react-dom';
import * as React from 'react';
import "core-js/modules/es.promise";
import "core-js/modules/es.array.iterator";

if (module.hot) {
    ReactDOM.render(<App />, document.getElementById('app'));
    module.hot.accept();
}

//App.tsx
import { store, persistor } from './redux/store';
import Framework from './layouts/Framework';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import * as React from 'react';
import { hot } from 'react-hot-loader/root'

class App extends React.Component {
    render() {
        return (
            <div>
                <Provider store={store}>
                    <PersistGate loading={null} persistor={persistor}>
                        <Framework />
                    </PersistGate>
                </Provider>
            </div>
        );
    }
}
export default hot(App);

总体

/ => 组件修改或浏览器刷新后浏览器热重载成功

/main, /firstComp, /secondComp 等... => 在浏览器中修改或刷新组件后,浏览器中的热重载失败。它显示无法获取/{页面地址}

我想从我的 webpack 中获取任何页面热重载。

谢谢。

【问题讨论】:

    标签: reactjs webpack react-router


    【解决方案1】:

    我以前没有见过这样的 webpack 设置,我按 id 分块,我会把这些部分贴在这里以防万一它对你有帮助。

    entry: "./src/App.js", // This is the component were I wrap routes in app
      output: {
        publicPath: './dist',
        path: path.resolve(__dirname, "dist"),
        filename: "[id].bundle.js",
        chunkFilename: "[id].js", // will auto assign a id to your separate chunks
      },
    
    import React from 'react';
    import Routes from './routes/routes'; // Figured I would show you that
    const App = () => {
        return ( <div><Routes /></div> );
    }
    
    export default App;
    
    resolve: {
        extensions: ["*", ".js", ".jsx", ".css", ".sa"]
      },
      plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new CompressionPlugin({
          cache: true,
          algorithm: "gzip",
          compressionOptions: {
            level: 5,                               
            minRatio: 0.8
          }
        }),
        new BundleAnalyzerPlugin({
          options: {
            generateStatsFile: true
          }
        }),
        new HtmlWebpackPlugin({
          template: "./public/index.html" // The path to your html
        })
      ],
      devServer: {
        contentBase: "./dist", // Where my file bundles are served from served from
        hot: true            // Enable hot loading
      },
      "devtool": "source-map"
    };
    

    然后在我的 index.js 中启用 hot;

    import App from './App';
    
    
    ReactDOM.render(<App />, document.getElementById('root'));
    module.hot.accept();
    

    在我发现我需要这些导入(也在 index.js 的顶部)之前,我无法让它正常工作

    import "core-js/modules/es.promise";
    import "core-js/modules/es.array.iterator";
    

    我没有任何经验的 webpack 有很多部分,所以希望这会有所帮助。

    【讨论】:

    • 添加信息后也是同样的问题。在你给我信息后,我用一些代码更新了我的帖子。请帮忙看看你是否有时间。谢谢
    • @Yang Jae Lee 在渲染到 dom 的下方,我的主索引中很热,而且我也不必导入它,webpack 将它添加到我的项目中。就像上面的例子
    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2013-11-10
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    相关资源
    最近更新 更多