2

Tonight I decided to start learning to use Webpack and Encore.

Just started and I already got a problem: Jquery does not exist in my templates but it does in my console.

How did i get here:

  • First I downloaded the depencies: composer require symfony/webpack-encore-bundle; yarn install; yarn add jquery --dev
  • Then, I built my assets: yarn encore dev --watch
  • I updated my assets/app.js file so it (should?) imports Jquery: ... import $ from 'jquery'; ...
  • Finally, I wrote my code in my templates/base.html.twig file:
        {{ encore_entry_script_tags('app') }}
        <script type="text/javascript">

            $(document).ready(function(){
                console.log('ok');
            })
        </script>
       {% block javascripts %}{% endblock %}

I did all this following Symfony documentation.

What I tried:

  • I tried playing with the import $ from 'jquery' line, using const, require, and so on...
  • I tried using <script src="{{asset('build/app.js')}}"></script>instead of {{ encore_entry_script_tags('app') }}.
  • I tried to build my assets as prod env instead of dev.
desertnaut
  • 57,590
  • 26
  • 140
  • 166
BadDev
  • 49
  • 6
  • https://stackoverflow.com/questions/2194992/jquery-is-not-defined https://stackoverflow.com/questions/8373357/jquery-is-not-defined-error https://stackoverflow.com/questions/8886614/uncaught-referenceerror-jquery-is-not-defined – FSDford Nov 18 '20 at 00:14
  • Nope, this is not working. – BadDev Nov 18 '20 at 00:19

2 Answers2

0

I fixed it by adding const $ = require('jquery'); global.$ = global.jQuery = $; in the assets/app.js file.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
BadDev
  • 49
  • 6
  • 2
    Please do not answer by editing/updating the question - post a complete answer in the answer space, as I have edited yours. – desertnaut Nov 18 '20 at 02:18
0

When you are using Webpack Encore you don't need to manually define jQuery via a Js file. You can simply include it in your WebpackConfig by adding the following to your webpack.config.js file:

Encore
  // your Encore config (outputPath, publicPath, ...)
  .autoProvidejQuery()

Which is equivalent to:

WebpackConfig.autoProvideVariables({
    $: 'jquery',
    jQuery: 'jquery'
});

Or when using Webpack without Encore:

var webpack = require('webpack')

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ],
}

When making changes to your webpack.config.js file, make sure to stop and restart Webpack / Encore.

Alessandro
  • 165
  • 10