skip to Main Content

With webpack-encore a script file could be added error free to a template with {{ encore_entry_script_tags('add-food') }} inside a properly formed JavaScript block. What is not at all clear is how to achieve the same effect with AssetMapper. The closest I ever get is something like this in a browser’s console: $ is not defined at add-food-81afe070e8be2f50bb5e13fa8d7573cf.js:1:1.

I’ve tried a wild variety of options without success. What am I missing?

Current environment:

../assets/vendor/installed.php:

// ...
  'jquery' => 
  array (
    'version' => '3.7.1',
    'dependencies' => 
//...

../assets/app.js:

import './bootstrap.js';

import './styles/app.css'
import './styles/jquery-ui.min.css'
import 'bootstrap/dist/css/bootstrap.min.css';
import './add-food.js';

import jquery from 'jquery';
const $ = jquery;
window.$ = $;

base.html.twig includes:

{# ... #}
{% block javascripts %}
    {% block importmap %}{{ importmap('app') }}{% endblock %}
{% endblock %}
{# ... #}

2

Answers


  1. Your problem here, in the error shown in the question, is not necessarily about creating a global variable.

    The error comes from add-food.js, which is imported before you create the global $ variable in app.js.

    You could try importing add-food.js after creating the global variable, but it looks like in this case, instead of creating a global variable, what you should to do is to import $ from 'jquery' on each script that needs it.

    The file will still be only requested once, and you won’t be creating an unnecessary global variable. (In any case, in your example the global variable should be created, although I’d probably do it like in the docs

    Login or Signup to reply.
  2. I had same problem with external packages where I cant put import. This solution works form me

    create script /assets/provide_jquery.js

    import $ from 'jquery';
    window.$ = window.jQuery = $;
    

    and in your main js file /assets/app.js
    add provide on top of your imports

    import './provide_jquery.js';
    import './bootstrap.js';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search