【问题标题】:Why doesn't the bundle.js get loaded on other routes?为什么 bundle.js 没有加载到其他路由上?
【发布时间】:2017-12-18 23:13:09
【问题描述】:

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

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

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

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

但是...这意味着 bundle.js 在 '/' 路径上加载了两次。通过 webpack 和 script 标签注入。

我怎样才能做到这一点,即使在重新加载时,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'))
});

【问题讨论】:

  • 您的服务器是否配置为将所有流量定向到基本 URL?你在用 react-router 吗?
  • 我更新了问题以包含对您问题的回答。

标签: javascript reactjs webpack-3


【解决方案1】:

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

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

对 webpack common 做了一个小改动。

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'),
    }),
  ],

【讨论】:

  • 就我而言,使用 publicPath 就足够了。感谢您的建议。
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 2016-03-20
  • 2021-01-25
  • 2020-12-20
  • 2019-07-03
  • 1970-01-01
相关资源
最近更新 更多