Cannot acces jQuery from Webpack Encore build file

647 views Asked by At

I am actually developping a website using Symfony, and their (simplified) version of webpack : Webpack Encore.

My website is using only one Javascript file, template.js, which uses jQuery and begins with a classic

$(document).ready(function(){ ... })(jQuery);

I would prefer to load jQuery from their CDN, and this is actually what I am doing. If I load the js/template.js script to the HTML file without using any webpack, everything works fine.

But, if I tell webpack to compile and output the js/template.js file content to build/app.js and include it in the HTML file, this happens :

Uncaught TypeError: $ is not a function
    at template.js:12
    at Object.<anonymous> (template.js:11)
    at Object../assets/js/template.js (app.js:1898)
    at __webpack_require__ (bootstrap 405ca97655117f294089:19)
    at Object.0 (jquery.js:10253)
    at __webpack_require__ (bootstrap 405ca97655117f294089:19)
    at bootstrap 405ca97655117f294089:62
    at bootstrap 405ca97655117f294089:62

Note: I think Webpack finds a way to tell the browser console that this actual code provides from js/template.js, but don't worry I am only using build/app.js.

So the problem is that now, my code cannot access jQuery. It's like if Webpack would surround my code in a scope where it cannot access anything outside.

Webpack adds some code before inserting the content of template.js in app.js, and here is how it actually begins inserting it :

/***/ "./assets/js/template.js":
/*!*******************************!*\
  !*** ./assets/js/template.js ***!
  \*******************************/
/*! no static exports found */
/*! all exports used */
/***/ (function(module, exports) {

(function ($) {
    $(document).ready(function () {

        if ($('.boxed .fullscreen-bg').length > 0) {
            $("body").addClass("transparent-page-wrapper");
        };

Finally, I tried the .autoProvideJquery() method from Encore, it changes some things in app.js but still doesn't work.

1

There are 1 answers

0
Scaraux On BEST ANSWER

The script couldn't access jQuery because of the this.jQuery

(function($){

    $(document).ready(function(){
        ...
    });

})(**this.**jQuery);

Replace by only jQuery