Webpack Encore - $ is not defined

落爺英雄遲暮 提交于 2019-12-06 06:33:02

问题


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 doesn't work.


回答1:


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

I had to write this in app.js :

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

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

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

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

Thank you for your help !




回答2:


You should use output.library: "Root" //Or what name you want config in webpack.config.js and in your entry js file do this:

import $ from 'jquery'

... Your code of common entry file

export {$};

And you will access jquery like this:

Root.$



来源:https://stackoverflow.com/questions/48971680/webpack-encore-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!