9

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.

Kristen Joseph-Delaffon
  • 1,261
  • 2
  • 17
  • 37

2 Answers2

38

Got it working by following the documentation.

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',
}))

Also make sure that the defer option is set to false:

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

Thank you for your help!

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
Kristen Joseph-Delaffon
  • 1,261
  • 2
  • 17
  • 37
  • Oh my god, THANK you for pointing me to the `defer: false`. I spend an hour banging my head against the wall because some symfony recipe update set that to true, and I wasn't aware of what it did. Man, thought I was going insane. – 94638857 Jul 18 '22 at 21:31
0

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.$

Martin
  • 201
  • 1
  • 4