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’s look at it progressively,

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

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.

Be advised, don’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.

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

 

That’s it!

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