使用Webpack与React-router时出现bundle.js未找到问题

18

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

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" 出现错误。看一下错误消息:这里

我的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');
    });

我不知道出了什么问题,请帮帮我!

3个回答

32

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

你应该在index.html中使用绝对路径来引用bundle.js

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

如果bundle.js与index.html在同一路径下,例如:

public/index.html

public/bundle.js

这将解决你的问题。

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

1
非常棒!我希望几个小时前就找到了那个答案 :p - challenger
5
但是我的index.html文件中没有bundle.js的内容,它以某种方式自动插入,并且使用相对路径。 - Curtis

17
如果您正在使用HtmlWebpackPlugin直接编辑index.html不是选项。因此,为了解决这个特定问题,在webpack.config.js中添加publicPath并将/指定为根文件夹即可:
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 开发服务器,以使这些更改生效。

有关 publicPath 的更多信息,请单击此处


1
它适用于我的项目。谢谢。(React 18,Webpack 5) - leoleozhu

13

在引入任何脚本之前,在我的index.html文件的标签中添加<base href="/" />对我有用。


你们根本不知道我花了多长时间来修复我的webpack配置(几天),结果发现这17个字符根本与webpack无关。谢谢。 - Michael Cox
@MichaelCox 啊,JS有时候挺有趣的。无论如何,干杯! - Peter

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