I'd like to use an external library in my custom module. So, I added it as a dependency in the composer.json of my custom module.

Since the drupal/recommended-project template places the vendor/ directory outside the webroot, we can't access it directly from the .libraries.yml file like this:

    /vendor/harvesthq/chosen/chosen.jquery.min.js: {}

According to this Jaypan's post, the solution for this issue is to use the Vendor Stream Wrapper module.
So, I added this module as a dependency, both in .info.yml and composer.json files of my module, following the example in the Jaypan's post.
Then I updated my .libraries.yml file:

    vendor://harvesthq/chosen/chosen.jquery.min.js: {}

However, the Chosen library is still not loaded (I mention that I cleared the Drupal cache) from what I see in my browser:

TypeError: $(...).chosen is not a function

Here is the dependencies declaration in the composer.json of my module:

"require": {
  "harvesthq/chosen": "^1.8",
  "drupal/vendor_stream_wrapper": "^1.3"

The dependency declaration in my .info.yml file:

  - vendor_stream_wrapper:vendor_stream_wrapper

The hook_form_alter() method in my .module file:

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form_object = $form_state->getFormObject();
  if ($form_object instanceof EntityFormInterface) {
    $entity = $form_object->getEntity();
    if (in_array($entity->getEntityTypeId(), ['node', 'user'])) {
      $form['#attached']['library'][] = 'my_module/chosen';

I mention that PHP goes well through the line $form['#attached']['library'][] = 'my_module/chosen';.

  • Is the file showing up in the HTML source? – Jaypan May 21 at 15:59
  • 1
    Use a Composer installer extender and have theme libs installed in a dedicated directory inside the webroot. Typically that's web/libraries/ or web/themes/custom/mytheme/libs. – leymannx May 21 at 18:56
  • 2
    You can find instructions for the installers extender method here: git.drupalcode.org/project/chosen/blob/8.x-2.x/README.txt if you decide to go down that route – Clive May 21 at 19:16
  • 1
    The code you've shown should be working. It looks fine. I'm suspecting it's something else in your system that will require some deeper debugging. I'm using the module exactly as you've described, and it works fine. – Jaypan May 23 at 14:27
  • 1
    You're right @Jaypan, it works on a clean Drupal installation. Good catch! I should have tested that... Thank you very much. – Kwadz May 24 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.