1

i am using webpack 4 for js bundling.jquery is working inside webpacked files.But not working inside html file.It showing below error

Uncaught ReferenceError: $ is not defined

webpack.config.js

 plugins: [
        new ExtractTextPlugin({filename:'css/app.bundle.css'}),
        new webpack.ProvidePlugin({
            $: "jquery",  
            jQuery: "jquery" 
        })
    ],

and i tried to call jquery inside index.html file,but i am getting undefind error

<script type="text/javascript">
  $(document).ready(function(){
    alert("here");
  })
</script>
Sandeep Nambiar
  • 1,656
  • 3
  • 22
  • 38

1 Answers1

4

There are many cases to make the error message. These are some:

1/. jQuery is not installed. Fix: npm i jquery

2/. $ refers to jQuery but the scope is not global.

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

By using this way, we define 2 global variables with the names $ and jQuery which refer to jquery. So,

Q: Where is the scope of that global?

A: Inside bundle.js file or any js file which is refered in webpack.config.js file:

entry: {
    'bundle.js': ['./assets/js/site', './assets/sdk/js/app']
}

In the file site.js and app.js, $ and jQuery are 2 global variables.

Every js file else cannot use $ and jQuery because of not defined.

Q: I just want to compile the 2 files site.js and app.js to the file bundle.js. But I still want to use jquery in any .html/.php/.cshtml... file(s), how can I do that?

A: Make jquery is global using window object. Like this:

site.js:

(function (global) {
    // $ and jQuery are function here...
    global.$ = $;
    global.jQuery = jQuery;
}(typeof window !== 'undefined' ? window : this));

Then,

<!-- bundle.js contains the code which makes $ refers to jquery, so we need to import it first -->
<script src="bundle.js"></script>
<script>
  // it should work
  $(document).ready(function(){
    alert("here");
  });
</script>

In other js files, we can use this way too. Or using 'require':

test.js:

var $ = require('jQuery');

Notice: In many cases, window may NOT an object in webpack, that why we need the line:

typeof window !== 'undefined' ? window : this

If you just write:

window.$ = $;

It may throw an error message like this:

window is not defined

Hope this helps!

Tân
  • 1
  • 15
  • 56
  • 102