jQuery, Webpack and Symfony | Call jQuery in your twig files

Uncaught ReferenceError: jQuery is not defined

If you encountered this error message in your console of a Symfony project using Webpack, it is very likely that you are using jQuery in the following way in your project : 

Your case


In the app.js file you probably called jQuery like this :

//app.js

const $ = require('jquery');

And then you wanted to call in your twig jQuery file this way :

//index.html.twig

<script>
    $("element");
</script>

And you came across this message: Uncaught ReferenceError: jQuery is not defined

The reason


This problem occurs because when calling jquery with the require() method, the app.js file will encapsulate jquery in its function which will only be visible by the code in the app.js file, so the index.html.twig file that calls jquery with a script tag will not be in the encapsulation and will not be able to call jquery.

My solution to call jQuery in twig


Instead of calling jQuery in the old way in your app.js file, proceed as follows:

//app.js

import $ from "jquery";
global.$ = $;

Now in any twig file, you can use jquery, after calling the app.js file of course, because it instantiates jquery.