Definición dinámica de librerías en Drupal 8

In Drupal 7, asset libraries were defined using hook_library_info(). This was mostly replaced by $module.libraries.yml files, see https://www.drupal.org/node/2201089.

For some advanced use cases — like detecting 3rd party libraries that need to be downloaded manually, and then exposing those as Drupal asset libraries (think Libraries API module) — you want to be able to still use PHP code to register libraries using some additional logic. That's why hook_library_info_build() was added

Note that "dynamic" doesn't mean "runtime" (i.e. for every request) — that'd be terrible for performance. The dynamically added libraries are still cached, just like libraries defined in YML files. It's "dynamic" because you can use logic to add libraries.

Dynamic libraries example

 

<?php
/**
 * Add dynamic library definitions.
 *
 * Modules may implement this hook to add dynamic library definitions. Static
 * libraries, which do not depend on any runtime information, should be declared
 * in a modulename.libraries.yml file instead.
 *
 * @return array[]
 *   An array of library definitions to register, keyed by library ID. The
 *   library ID will be prefixed with the module name automatically.
 *
 * @see core.libraries.yml
 * @see hook_library_info_alter()
 */
function hook_library_info_build() {
  $libraries = [];
  // Add a library whose information changes depending on certain conditions.
  $libraries['mymodule.zombie'] = [
    'dependencies' => [
      'core/backbone',
    ],
  ];
  if (Drupal::moduleHandler()->moduleExists('minifyzombies')) {
    $libraries['mymodule.zombie'] += [
      'js' => [
        'mymodule.zombie.min.js' => [],
      ],
      'css' => [
        'base' => [
          'mymodule.zombie.min.css' => [],
        ],
      ],
    ];
  }
  else {
    $libraries['mymodule.zombie'] += [
      'js' => [
        'mymodule.zombie.js' => [],
      ],
      'css' => [
        'base' => [
          'mymodule.zombie.css' => [],
        ],
      ],
    ];
  }

  // Add a library only if a certain condition is met. If code wants to
  // integrate with this library it is safe to (try to) load it unconditionally
  // without reproducing this check. If the library definition does not exist
  // the library (of course) not be loaded but no notices or errors will be
  // triggered.
  if (Drupal::moduleHandler()->moduleExists('vampirize')) {
    $libraries['mymodule.vampire'] = [
      'js' => [
        'js/vampire.js' => [],
      ],
      'css' => [
        'base' => [
          'css/vampire.css',
        ],
      ],
      'dependencies' => [
        'core/jquery',
      ],
    ];
  }
  return $libraries;
}
?>