Assets and libraries
Working with CSS and JS files in Drupal is done using libraries. So, let’s see how they work by going through some examples.
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 some information about it. We can specify a version number and then add as many CSS and JS file references as we need. The file paths are relative to the module folder this library...