Libraries overrides not working or removing assets

The Libraries API in Drupal is very powerful and flexible, but it may come with a cost - it may fail in some cases, like the libraries-override definition.

While working with the color module and sub- and parent themes, things may fail, especially when you need to exclude some assets from the parent theme.

I have this setup at hand - the sub-theme extends the parent theme and excludes bundle.css (a big compiled CSS file). While it should be fine in theory, it fails when the color module comes into play - it is altering the parent theme assets path, and libraries-override fails because of that. One additional condition must be met as well - the parent theme should have previously saved color settings, which may not make sense but may happen while testing, accidentally, etc.

Anything that touches assets paths may cause this issue, and most likely, any library-related thing fails. There are some ways I can think of how to handle it:

  • split library definitions and remove library definition completely in sub-theme
  • use hook_library_info_alter() inside sub-theme

Below you can find the code snippet for removing the asset file with hook_library_info_alter()

File: my_theme/my_theme.theme
/** * Implements hook_library_info_alter(). */ function my_theme_library_info_alter(&$libraries, $extension): void { if ($extension === 'parent_theme' && isset($libraries['main']['css']['theme'])) { foreach (array_keys($libraries['main']['css']['theme']) as $path) { if (str_contains($path, '/bundle.css')) { unset($libraries['main']['css']['theme'][$path]); } } } }
Buy Me a Coffee at ko-fi.com

Add new comment