2

I am working with reactjs and I need to import $ globally in my webpack.

I know I can import in each component like this

import $ from 'jquery'

But it is being used in every component so I want to avoid from writing it in every component. So how do I do this using webpack or there is any other way to do this

I have added this in webpack but stills doesn't work

  module: {
    strictExportPresence: true,
    rules: [
      {
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: '$'
        }]
      }
    ],
  },

Any help would be appreciated!!!

Dark Knight
  • 995
  • 4
  • 22
  • 48
  • 1
    Oftopic from your question, but why would you need jquery in every component? That alone raises serious questions. Could you show a sample of the problems that you are solving with jquery? If you do any DOM manipulation with it, then you shouldn't use reactjs at all... – Icepickle Oct 10 '18 at 08:19
  • I want to open the bootstrap modal popup with jquery `$('#WelcomeModal').modal('show')`. I did found something here https://stackoverflow.com/questions/29080148/expose-jquery-to-real-window-object-with-webpack. But unfortunately doesn't work. Please help!!! – Dark Knight Oct 10 '18 at 08:20
  • In every component? Can't you centralize it in your app, or on route changes? – Icepickle Oct 10 '18 at 08:22
  • Almost in every component. – Dark Knight Oct 10 '18 at 08:24

1 Answers1

1

Use ProvidePlugin

https://webpack.js.org/plugins/provide-plugin/

plugins: [ new webpack.ProvidePlugin({$: 'jquery'}) ]
Håken Lid
  • 22,318
  • 9
  • 52
  • 67