Asset Autoload scans modules and themes for CSS and JS files and generates library definitions based on the filenames of discovered files. Then, it automatically attaches the libraries that match any theme suggestions of rendered templates.

Configuration

Asset Autoload is configured through the asset_autoload option in a module or theme's *.info.yml file.

Pass true to scan the entire module or theme for assets:

asset_autoload: true

Pass a string to scan a single directory only:

asset_autoload: templates

Pass an array to scan multiple directories:

asset_autoload:
  - templates
  - components
  - etc.

Automatic library definitions

The configured directories are scanned recursively for files ending in .css or .js. Each file is added to a library definition using the filename as the library name.

Automatic library attachment

When a template rendered, libraries that match any of the theme suggestions are automatically attached. This includes libraries from installed modules, the active theme, and all base themes of the active theme.

Using suggestions as classes

An additional variable, suggestions, is provided to all preprocess functions. It contains an array of theme suggestions of the given template.

You may optionally add the suggestions as HTML classes:

use Drupal\Core\Template\AttributeHelper;

function mytheme_preprocess(&$variables) {
  $variables['attributes'] = AttributeHelper::mergeCollections(
    $variables['attributes'] ?? [],
    [ 'class' => $variables['suggestions'] ],
  );
}

Similar projects

Supporting organizations: 

Project information

Releases