4

I am attempting to use jQuery as $ in my webpack application's entry index.js file, and I am receiving this error when running my application in the browser:

Uncaught TypeError: Cannot read property 'fn' of undefined

This is due to a line in a module I am importing called bootstrap-switch, and the line in question is:

$.fn.bootstrapSwitch = function() {

So I do not have $ working as a global variable. I followed instructions on the ProvidePlugin docs, as shown below. I also tried the answer provided in this question but that didn't work.

This is an abbreviated version of my webpack.config.js file:

module.exports = {
    entry: {
        main: './src/index.js'
    },
    plugins: {
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'
        })
    }
}

And this is my src/index.js file:

import 'bootstrap-switch';

console.log('I am running');

Any help would be much appreciated.

EDIT

A previous version of this question asked about a build error that was actually an ESLint error. Thank you to @UjinT34 for helping me resolve that problem and focus on the actual error outlined above.

Matt
  • 23,363
  • 39
  • 111
  • 152
  • I had a similar issue with a legacy jQuery plugin wanting to use the jQuery from the `window` — it wanted `window.jQuery`, but yours might be after `window.$`. https://stackoverflow.com/a/48690626/5796134 – Ito Pizarro Mar 08 '19 at 20:39
  • Aaaaaand there we go! Yes, that was the problem! Very sneaky of the plugin. It uses a self-executing function to initialize, and passes itself `window.jQuery`. Adding in the configuration from the linked question's answer solved this problem. If you'd like to link to it in an answer, I will accept it. – Matt Mar 08 '19 at 20:44

2 Answers2

4

no-undef is a ESlint error. It doesn't know about your webpack setup. You can specify global variables in esling config:

{
    "globals": {
        "$": "readonly",
        "jQuery": "readonly"
    }
}
UjinT34
  • 4,784
  • 1
  • 12
  • 26
  • 1
    Thanks, and you were right, that cleared that ESLint error. But see my "additional note" above: when I run my application, I get an error inside `bootstrap-switch.js`: `Uncaught TypeError: Cannot read property 'fn' of undefined`. And on the line in question, the code is: `$.fn.bootstrapSwitch = function() {`. So it seems like `$` isn't making it as a variable to that module, which I am importing in my `src/index.js` entry point. This is the root point of my question, now that we cleared the ESLint error. Any ideas? – Matt Mar 08 '19 at 20:22
4

I'm adding this as an answer for future users to find.

Try adding 'window.jQuery': 'jquery' to your webpack.ProvidePlugin() settings.

module.exports = {
    ...
    plugins: [
        new webpack.ProvidePlugin( {
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        } )
    ]
};
Ito Pizarro
  • 1,607
  • 1
  • 11
  • 21