javascriptjquerysymfonywebpack-encore

How to use jQuery with webpack-encore in a Symfony project?


I have a problem with webpack-encore and jQuery. I have a custom.js file with this code:

import "../css/custom.css";

var $ = require("jquery");

global.$ = global.jQuery = $;

And in the twig file i have this code:

<script src="{{asset('build/js/custom.js')}}"></script>
<script>
    $(document).ready(function (){
        alert("1");
    })
</script>

The path to custom.js passed as argument is correct.

When I compile with yarn run encore dev jQuery module is not inside the generated file for custom.js but is in another file named 0.b9e94bd1.js.

The problem is that it gives me the error $ is not defined

How can I solve this problem?


Solution

  • I solved the issue. I changed asset function inside the twig with encore_entry_script_tags, now jQuery and $ are defined.