< Go Back Home

Webpack Encore jQuery not defined

Yeap, jQuery is still relevant in some cases and within WebPack, it causes a bit of an issue when being imported. The reason, in most cases, is jQuery being defined as $ and not as jQuery. Depending on how your jQuery specific code was written, it could render it not working. Let&#8217;s look at it progressively,

const $ = require('jquery');

This is probably how you included jQuery in your app.js file. The only problem is, this however doesn&#8217;t declare jquery as a global $ or jQuery. And you end up with something like the following,

Uncaught ReferenceError: $ is not defined at [...]
Uncaught ReferenceError: jQuery is not defined at [...]

The solutions also depend on the use case,

Expecting jQuery to be Global

If you are using a plugin that expects jQuery to be global via $ or jQuery, your best bet is to add `autoProvidejQuery()` to your encore webpack.config.js file.

Encore
    // ...
    .autoProvidejQuery()
;

Be advised, don&#8217;t use .autoProvideVariables(), they are the same. `autoProvidejQuery()` is working on top of it, just for jQuery.

What about Embedded Scripts?

Your page might have a few Embedded scripts that require jQuery. In cases like that, one simple line should fix your issue, Go Global.

global.$ = global.jQuery = $;

On your app.js file, add this after you have included your jquery.

&nbsp;

That&#8217;s it!

If you are using Symfony ( you should ), take a look here # https://symfony.com/doc/current/frontend/encore/legacy-applications.html 

&nbsp;