Categories
CMS Drupal Mastering Development

How to include external libraries placed outside the webroot in a custom module?

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:

chosen:
  js:
    /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:

chosen:
  js:
    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:

dependencies:
  - 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';.

Leave a Reply

Your email address will not be published. Required fields are marked *