简体   繁体   English

如何在 Symfony 项目中使用带有 webpack-encore 的 jQuery?

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

I have a problem with webpack-encore and jQuery.我有 webpack-encore 和 jQuery 的问题。 I have a custom.js file with this code:我有一个带有以下代码的 custom.js 文件:

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.作为参数传递的 custom.js 的路径是正确的。

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 .当我使用yarn run encore dev编译时,jQuery 模块不在custom.js生成的文件中,而是在另一个名为0.b9e94bd1.js文件中。

The problem is that it gives me the error $ is not defined问题是它给了我错误$ 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.我使用 encore_entry_script_tags 更改了树枝内部的资产功能,现在定义了 jQuery 和 $。

I suggest you to uncomment this line in webpack.config.js我建议你在 webpack.config.js 中取消注释这一行

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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