【问题标题】:Using Webpack with React-router bundle.js Not Found使用 Webpack 和 React-router bundle.js Not Found
【发布时间】:2016-10-24 01:44:19
【问题描述】:

我用 Webpack 和 react-rounder 构建了一个项目。 这是我的代码:

ReactDOM.render(
    <Provider store={store}>
        <Router history={ browserHistory }>
            <Route path='/' component={ App } >
                <IndexRoute component={ Home } />
                <Route path="purchase" component={ Purchase } />
                <Route path="purchase/:id" component={ Purchase } />
            </Route>
        </Router>
    </Provider>,
    document.getElementById('example')
);

当我请求"http://127.0.0.1:3001/purchase" 时,它成功了!但地址"http://127.0.0.1:3001/purchase/a" 有错误。查看错误信息:enter image description here

我的 WebpackDevServer 配置是:

new WebpackDevServer (webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    noInfo: false,
    historyApiFallback: true
}).listen(3001, '127.0.0.1', function (err, result) {
        if (err) {
            console.log(err);
        }
        console.log('Listening at localhost:3001');
    });

我不知道怎么回事,帮帮我!

【问题讨论】:

    标签: javascript reactjs webpack react-router


    【解决方案1】:

    您正在使用相对路径来描述 index.html 中 bundle.js 的路径。

    您应该在 index.html 中使用 bundle.js 的绝对路径

    绝对路径包含根目录以及包含文件或文件夹的所有其他子目录。

    如果它与您的 index.html 位于同一路径中。

    例如。

    public/index.html

    public/bundle.js

    这会解决你的问题。

    <script src="/bundle.js"></script>
    

    【讨论】:

    • 非常棒!我希望我能在几个小时前找到答案:p
    • 但是我的 index.html 文件中没有 bundle.js,它以某种方式自动插入并带有相对路径。
    【解决方案2】:

    在包含任何对我有用的脚本之前,将 &lt;base href="/" /&gt; 添加到我的 index.html 文件的 head 标记中。

    【讨论】:

    • 你不知道我尝试修复 webpack 配置多长时间(几天)才发现这 17 个字符甚至与 webpack 无关。谢谢。
    • @MichaelCox 啊,JS 有时很有趣。无论如何干杯!
    【解决方案3】:

    如果您碰巧使用HtmlWebpackPlugin 编辑直接index.html不是一个选项。因此,要解决此特定问题,请添加 publicPath 并将 / 指定为 webpack.config.js 内的根文件夹:

    const path = require('path')
    
    module.exports = {
      entry: './app/index.js',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/'
      },
      // more config stuff goes below..
    } 
    

    不要忘记重启 webpack 开发服务器以使这些更改生效

    关于publicPathhere的更多信息。

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 1970-01-01
      • 2017-05-11
      • 2020-07-23
      • 1970-01-01
      • 2017-05-11
      • 2017-09-13
      • 2020-03-04
      • 1970-01-01
      相关资源
      最近更新 更多