Search code examples
symfonywebpack-encore

How can I access JQuery ($) from a template in Symfony 6 with Encore?


How can I access JQuery $ from a template? I am able to access it in app.js, but $ is not defined when I try to run the code in a template.

mypage:480 Uncaught ReferenceError: $ is not defined

I'm using Symfony 6 with Encore installed.

app.js

...
const $ = require('jquery');
global.$ = global.jQuery = $;
// test code
$(document).ready(function() {
    alert('success from app.js');
})

webpack.config.js

...
 .autoProvidejQuery()

webpack_encore.yaml

...
  script_attributes:
        defer: true

base.html.twig (my page template's parent)

...
{% block javascripts %}
    {{ encore_entry_script_tags('app') }}
{% endblock %}

My page template:

...
{% block javascripts %}
    {{ parent() }}
    <script>
      // THIS CODE TRIGGERS THE ERROR
      $(document).ready(function() {
        alert('success from template!');
      })
    </script>
{% endblock %}


Solution

  • You have to be sure that you have defer to false in your encore config component:

    # config/packages/webpack_encore.yaml
    webpack_encore:
        # ...
        script_attributes:
            defer: false
    

    Source : https://symfony.com/doc/6.0/frontend/encore/legacy-applications.html