Brave publisher PUBLISHER
Web developer Front-End in Oise, France - Gary Deshayes

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


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 5 | Return an image via a controller route

Symfony

Created at : Wednesday 1 September 2021

VueJS 3, ExpressJS 4.17 | Uploading and resizing an image

Javascript Framework JS

Created at : Saturday 28 November 2020

Symfony Event Subscriber | Restricting an ip range with an Event Subscriber

Symfony

Created at : Saturday 14 November 2020

Angular, ExpressJS | JWT authentication with Angular 10 and ExpressJS 4 (MySQL)

Javascript SQL Framework JS

Created at : Sunday 20 September 2020

Symfony, Excel, CSV | Generating a CSV file for Excel with Symfony

Symfony

Created at : Thursday 6 August 2020

Symfony FormType Choice | Set data default to group of radio button

Symfony

Created at : Sunday 26 July 2020

Doctrine, Symfony | Difference between two dates in MySQL (Day, month, year...)

Symfony SQL

Created at : Thursday 18 June 2020

JavaScript, jQuery et Regex | Secure a password in real time with JS

Javascript jQuery

Created at : Monday 23 March 2020

Symfony, Doctrine | Retrieve old data of FormType

Symfony

Created at : Friday 14 February 2020

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

Symfony Bugs

Created at : Sunday 26 January 2020