jQuery loaded with ProvidePlugin in Webpack 2 does't work after route change

87 Views Asked by At

I am working in Angular4 and I am using Webpack setup for building the app. I want to use jQuery in my project so I googled it and found about the ProviderPlugin that is offered by Webpack to globally load modules.

However, the issue I am facing is a bit strange; the first time when the page loads the page works fine and all the code which is associated with jQuery works fine but when I change the page or route the jQuery loses its functionality and consequent pages don't work as expected. Am I missing something, the code I used for plugin is standard

new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' })

I am looking for other solutions as well, if there are other ways to do then please mention it would be a great help.

Thank you so much.

1

There are 1 best solutions below

3
On

Also you can use the HtmlWebpackPlugin that will create your html pages. And set inject:true. Because you issue probably is when you try to access to another page the jquery isn't declared, so you need a main template page that has jquery and from this template, create the next html pages. Example bellow:

new HtmlWebpackPlugin({
  filename: 'index.html',
  template: 'index.html',
  inject: true
})

So download the package in npm, configure, install it then set up.

Also you can edit you jquery insertion with this:

new webpack.ProvidePlugin({
  $: 'jquery',
  jquery: 'jquery',
  'window.jQuery': 'jquery', 
  jQuery: 'jquery'
})