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

Web developer Front-End in Oise, France - Gary Deshayes <--Traduction

Created at : Sunday 26 January 2020


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.

News publications :
Symfony

Created at : Monday 1 November 2021

Javascript Framework JS

Created at : Sunday 31 October 2021

Symfony

Created at : Wednesday 1 September 2021

Javascript Framework JS

Created at : Saturday 28 November 2020

Javascript SQL Framework JS

Created at : Sunday 20 September 2020

Symfony

Created at : Thursday 6 August 2020

Javascript jQuery

Created at : Monday 23 March 2020

Symfony

Created at : Friday 14 February 2020

Symfony Bugs

Created at : Sunday 26 January 2020