为什么bundle.js不会在其他路由上加载?

问题描述 投票:1回答:1

我在webpack.common.js文件中使用webpack3加载我的bundle.js并输出如下。

当我使用React前端点击'/'路线时,这很好用。我的React路由器工作正常并按预期在应用程序中导航,根据需要更改URL。

但是当我使用不是'/'的URL重新加载浏览器时,bundle.js不会自动注入。

作为解决方法,我在index.html模板中引用了一个脚本标记,引用了bundle.js。这解决了其他路线上的问题。

但是......这意味着bundle.js在'/'路由上加载了两次。通过webpack和脚本标记注入。

我怎样才能使bundle.js在重载时被注入所有路由,或者如何在模板中保留脚本标记以防止webpack 3自动注入bundle.js?

  entry: {
    app: './client/src/index.jsx',
   },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname + '/dist'),
    publicPath: '/'
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Shopping',
      template: './index.html',
    }),

该项目正在使用ReactRouter 4,并且从浏览器到服务器的每次调用都会触发此路由:

app.get('*', (req,res) =>{
  res.sendFile(path.resolve(__dirname, '../index.html'))
});
javascript reactjs webpack-3
1个回答
0
投票

我在这里找到了一个解决方案https://stackoverflow.com/a/43704661/5086349。我保持标签在我的模板中引用bundle.js然后设置停止束注入。

<script type="text/javascript" src="/app.bundle.js"></script>

对webpack常见做了一点改动。

output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname + '/dist'),
    publicPath: '/'
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({


      // Set inject to false. 
      inject: false,


      title: 'Shopping',
      template: './index.html',
    }),
    new webpack.HotModuleReplacementPlugin(),
    new ServiceWorkerWebpackPlugin({
      entry: path.join(__dirname, './client/components/user/sw.js'),
    }),
  ],
© www.soinside.com 2019 - 2024. All rights reserved.