Score:1

How do I alias jQuery to $ before loading a remote library?

iq flag

I am trying to use Bootstrap autocomplete in my module. I added this to my .libraries.yml.

bootstrap-autocomplete:
  remote: https://bootstrap-autocomplete.readthedocs.io/en/latest/
  version: 2.3.7
  license:
    name: MIT
    url: https://getbootstrap.com/docs/4.0/about/license/
    gpl-compatible: true
  dependencies:
    - core/jquery
  js:
    https://cdn.jsdelivr.net/gh/xcash/[email protected]/dist/latest/bootstrap-autocomplete.min.js: { type: external, minified: true, async: true, defer: true }

I get this in the HTML markup, which looks fine (until the tests prove otherwise, of course).

<script src="/CLS/core/assets/vendor/jquery/jquery.min.js?v=3.5.1"></script>
[...]
<script src="https://cdn.jsdelivr.net/gh/xcash/[email protected]/dist/latest/bootstrap-autocomplete.min.js"></script>

On page loading I get the classic Uncaught TypeError: $ is not a function. Of course, as I well know, jQuery is not aliased to $ in Drupal if called outside the usual closures.

I know I shouldn't alias jQuery to $ in the global namespace, but I cannot think of any better solution.

Is there a solution I should use?

ru flag
Are you sure just including the library is causing this error? Often libraries don't do anything until you have some local javascript initializing the library like `$('.my_input_field').autoComplete();`. In the latter case, move that local code inside a [Drupal behavior](https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview)
Francesco Marchetti-Stasi avatar
iq flag
@Hudri, I guess you are right, I did a quick check repeating what I wrote yesterday and I didn't get the error, so I guess that when I got it I had an instantiation in place. I am using the past because after realizing that bootstrap-autocomplete is not part of the bootstrap core and that I was entering dependency hell I switched to a custom autocomplete implementation, so I no longer have the problem anyway...
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.