Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery not available as "$" when using webpack's ProvidePlugin

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.

like image 701
MegaMatt Avatar asked Jan 27 '23 15:01

MegaMatt


1 Answers

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'
        } )
    ]
};
like image 156
Ito Pizarro Avatar answered Jan 30 '23 11:01

Ito Pizarro