Assets and libraries
Working with CSS and JS files has become standardized in Drupal 8 compared to its previous version where we had more than one way to do things. And this, of course, continues in Drupal 9. Libraries are key, so let's see how they work by going through some examples of making use of some CSS or JS files.
There are three steps to adding assets to your page:
- Creating your CSS/JS file
- Creating a library that includes them
- Attaching that library to a render array
Libraries
Assuming that you already have the CSS/JS files, libraries are defined inside a module_name.libraries.yml
file in the module root folder. A simple example of a library definition inside this file would look like this:
my-library: version: 1.x css: Â Â Â theme: Â Â Â Â Â css/my_library.css: {} js: Â Â Â js/my_library.js: {}
This is a standard YAML notation by which we define a library called my-library
and provide...