3) Libraries - Including JavaScript and CSS in Drupal 8 Themes

November 27, 2015

Lessons From the Road

Back in 2014, I set out on an adventure with Memorial Sloan Kettering and multiple web and design agencies to begin building the first fully-operational, enterprise-level Drupal 8 website. We succesfully launched the site in May of 2015. I want to share some of the real-world lessons I learned over the past year, so that hopefully you can start adopting Drupal 8.

Libraries - Including JS and CSS

JS and CSS are included in D8 via libraries.

Using libraries in our themes keeps development more consistent between creating custom modules and custom themes. One major advantage to this approach is that libraries provide the ability use dependencies to insure proper source order of JS libraries. So we no longer need to rely only on fiddling around with weights and scopes.

Declare the library in .info.yml

We need to make Drupal aware that this theme has a library. To do so,
in the themes THEMENAME.info.yml file, we declare the library.

It is a good idea to namespace your library name (by prepending it with a unique site or theme abbrevation) so that you don’t unintentionally declare the same library name as some other module, etc.

Note: Libraries silently fail if they don’t load.

Create libraries.yml file

Create a file THEMENAME.libraries.yml in your theme folder. This file will list out and define all of your libraries. A given library can include both CSS and JS. (The above examples have them separate.)

The curly brackets contain additional parameters, and must be present even if no paramaters are being passed.

dependencies: This lists out other libraries upon which this library depends. You can refer to core libraries or other libraries defined in this same libraries.yml file of the theme.

Look in core/core.libraries.yml (and search through all *libraries.yml files in core) to find the names of libraries that you may need to list as dependencies and to find many examples of how to define libraries and use parameters.

Example JS Parameters

every_page: true,

weight: -22,

browsers: { IE: ‘lte IE 8’, ‘!IE’: false },

minified: true

preprocess: 0,

scope: header, footer

Written by Brad Wade

Brad Wade is a front-end web developer, Drupal specialist, and musician living in New York City.