Webpack Encore - $未定义。

9

我将按照文档说明来使Webpack Encore在我的项目中工作。 在webpack.config.js中导入的js文件正常工作,但是在特定于页面的js中存在问题:$未定义

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无法工作。
2个回答

39

通过遵循文档,我把它搞定了。

我必须在app.js中编写以下内容:

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

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

我从webpack.config.js中删除了这段代码,因为它等同于.autoProvidejQuery

而我从 webpack.config.js 中移除了这个,因为它相当于 .autoProvidejQuery

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

还要确保defer选项设置为false:

# config/packages/webpack_encore.yaml
webpack_encore:
  script_attributes:
    defer: false

谢谢你的帮助!


哦,我的天啊,感谢你指出defer: false。因为某个Symfony配方更新将其设置为true,而我不知道它的作用,所以我花了一个小时撞墙。我还以为我要疯了。 - 94638857

0

你应该在webpack.config.js中使用output.library: "Root" //或者你想要的名字配置,并在入口js文件中执行以下操作:

import $ from 'jquery'

... 你的通用入口文件代码

export {$};

这样你就可以像这样访问jquery:

Root.$


1
我尝试了两种方法,但仍然出现“$未定义”或“jquery未定义”的错误。 - Kristen Joseph-Delaffon
你试过使用 jQuery 而不是 jquery 吗? - Martin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接