简体   繁体   中英

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?

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

I suggest you to uncomment this line in webpack.config.js

     // uncomment if you're having problems with a jQuery plugin
    .autoProvidejQuery()

see https://symfonycasts.com/screencast/webpack-encore/autoprovide-jquery-modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM