Webpack Encore-未定义$ [英] Webpack Encore - $ is not defined

查看:124
本文介绍了Webpack Encore-未定义$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了文档,以使Webpack Encore在我的项目中工作. 在webpack.config.js中导入的js文件可以正常工作,但是在特定于页面的js中存在一个问题:$ is not defined.

I followed the documentation to make Webpack Encore work in my project. Imported js files in webpack.config.js work fine but I have an issue in page-specific js : $ is not defined.

Webpack.config.js :

const Encore = require('@symfony/webpack-encore');
var webpack = require('webpack');

Encore
.setOutputPath('public/build/')
.setPublicPath('http://localhost/tharmo/public/build')
.setManifestKeyPrefix('build/')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.autoProvidejQuery()

.createSharedEntry('vendor', [
    './assets/js/custom.js',
    'materialize-css',
])
.addEntry('app', './assets/js/app.js')
.addEntry('statistiques', './assets/js/statistiques.js')
.addPlugin(new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery',
}))

.enableSassLoader()
;

module.exports = Encore.getWebpackConfig();

base.html.twig :

<script src="{{ asset('build/manifest.js') }}"></script>
<script src="{{ asset('build/vendor.js') }}"></script>
<script type="text/javascript" src="{{ asset('build/app.js') }}"></script>
<script>
    $(document).ready(function () {
        getNotifications(1);
    });
</script>

$(document).ready不起作用.

推荐答案

请按照以下文档进行操作:

Got it working by following the documentation : https://symfony.com/doc/current/frontend/encore/legacy-apps.html

我必须在app.js中编写它:

I had to write this in app.js :

// require jQuery normally
const $ = require('jquery');

// create global $ and jQuery variables
global.$ = global.jQuery = $;

我从webpack.conig.js中删除了它,因为它等效于.autoProvidejQuery:

And I removed this from webpack.conig.js since it's equivalent to .autoProvidejQuery :

.addPlugin(new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery',
}))

谢谢您的帮助!

这篇关于Webpack Encore-未定义$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆