Jason Allshorn
Jason Allshorn

Reputation: 1625

Why doesn't the bundle.js get loaded on other routes?

I load my bundle.js and output as below using webpack3 in a webpack.common.js file.

This works fine when I hit the '/' route with a React front end. My React router works fine and navigates around the app as expected changing the urls as needed.

But when I reload the browser from with a url that is not '/' the bundle.js is not automatically injected.

As a work around I put a script tag in the index.html template referencing the bundle.js. Which fixes the problem on the other routes.

But... It means the bundle.js loads twice on the '/' route. By being injected by webpack and also from the script tag.

How can I make it so that either the bundle.js gets injected on all routes even on reload, or how can I keep the script tag in the template prevent webpack 3 from automatically injecting the 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',
    }),

The project is using ReactRouter 4 and every call from the browser to the server hits this route:

app.get('*', (req,res) =>{
  res.sendFile(path.resolve(__dirname, '../index.html'))
});

Upvotes: 1

Views: 1758

Answers (1)

Jason Allshorn
Jason Allshorn

Reputation: 1625

I found a solution here https://stackoverflow.com/a/43704661/5086349 . I kept the tag referencing the bundle.js in my template then set stopped the bundle injection.

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

Made a small change to the 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'),
    }),
  ],

Upvotes: 1

Related Questions