Webpack Encore - $ 未定义 [英] Webpack Encore - $ is not defined
本文介绍了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
不起作用.
推荐答案
按照文档操作: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屋!
查看全文