Skip to main content

Drupal 8.x hook_library_info_alter Usage example

Dynamically generated CSS and JS

Usage / Example

In extremely rare and advanced cases, you may have the need to dynamically generate CSS and JS. Like adding CSS/JS from Admin settings based files (Dev, Prod, min etc). In below example will alter library dynamically.

First define Lib in MYMODULE.libraries.yml

some-lib:
  header: true
  js:
    https://website.com/js/jsfile.min.js: { type: external, minified: true }

Now attach this Lib to site or any section

Next is to define hook_library_info_alter 

function MYMODULE_library_info_alter(&$libraries, $extension) {
  if ($e == 'MYMODULE') {
    $config = \Drupal::config('MYMODULE.adminsettings');
    $environment  = $config->get('env');
    if ($environment == 'dev') {
      $alt = [
        'https://website.com/js/jsfile.js' => [
          'type' => 'external',
          'minified' => FALSE,
        ]
      ];
      $l['some-lib']['js'] = $alt;
    }
  }
}

Clear site cache, Now Lib will be used files based on variable / settings defined.