Webpack-encore: jQuery error: $ is not defined / Can't find variable: $ even using legacy workaround

Created on 30 Mar 2021  路  4Comments  路  Source: symfony/webpack-encore

After upgrading to Symfony 5.2.6 (and applying the updated recipes), I "again" encountered the issue in javascript console.

$ is not defined
Can't find variable: $

Same as issue #32 but reappearing after updates.

Our code needs access to $ or jQuery variables outside of JavaScript files processed by Webpack.
I verified my webpack.config.js and my app.js folowing instructions found in Symfony Doc jQuery Plugins and Legacy Applications :

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

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

This workaround doesn鈥檛 work and I still have the error.

Most helpful comment

using deferred scripts is indeed not compatible with legacy applications wanting to use in-page scripts referencing things exposed by the JS file managed by webpack (or any other tool for that matter), as the execution would not be guaranteed.
I think that the doc should indeed be updated to mention that defer must be disabled for such case.

All 4 comments

webpack-encore-bundle 1.9 introduces script attributes : "defer".
https://github.com/symfony/recipes/blob/master/symfony/webpack-encore-bundle/1.9/config/packages/webpack_encore.yaml

    # Set attributes that will be rendered on all script and link tags
    script_attributes:
        defer: true

Symfony recipes set this option to true in config/packages/webpack_encore.yaml
If this option is set to true "global" workaround describe in jQuery Plugins and Legacy Applications doesn鈥檛 work.

Setting this to false fixed the error.

Do we have to update Symfony documentation to prevent errors and to explain what does this new attribute ?

using deferred scripts is indeed not compatible with legacy applications wanting to use in-page scripts referencing things exposed by the JS file managed by webpack (or any other tool for that matter), as the execution would not be guaranteed.
I think that the doc should indeed be updated to mention that defer must be disabled for such case.

@nicohery have you tried expose-loader?

Indeed, documentation issue - closed by https://github.com/symfony/symfony-docs/pull/15280

Was this page helpful?
0 / 5 - 0 ratings