How? #

Attaching a library follows the standard Drupal way. On top of a .html.twig file you can attach a library as follows:

Twig Created with Sketch.
node.html.twig
{{ attach_library('my-theme/node') }}

When attaching libraries in a template that is extending, the standard becomes:

Twig Created with Sketch.
node.html.twig
{% block before %}{% endblock %}

<article>...</article>
Twig Created with Sketch.
node--full.html.twig
{% extends 'node.html.twig' %}

{% block before %}
  {{ attach_library('my-theme/node--full') }}
{% endblock %}

Make sure that the base component, has a "before" block tag defined, empty, and on top of the file.

Why so many libraries? #

You can think of the concept of “attaching a library” as linking assets such as CSS or JS to HTML. For Drupal, this means: If I am going to use that .html.twig file, I should also send along the assets it's attached library.

In the context of aggregating CSS/JS it makes sense too: If Drupal is about to render a page, it will make a list of all the templates it needs for that page. Not only that, it will also list all the assets of each of those templates, aggregate them together and send them along with the page.

It also means that the more we split up our assets in to libraries, the leaner our page becomes. If you analyse the CSS of any custom theme on a page of a site that doesn’t use a component-approach, we could see that the actual useful CSS will be close to 10% of the loaded CSS.

Combining libraries #

card
dist
css3-full Created with Sketch.
card.css
js-badge Created with Sketch.
card.js
YAML Created with Sketch.
libraries.yml
js-badge Created with Sketch.
card.js
sass Created with Sketch.
card.scss

Components can exist without having their own .html.twig file. In other words, libraries can be defined without being attached to the .html.twig file of the component itself. 

This could be the case for libraries that are meant to be used in combinations with other components.

Let’s take the example of creating a component called card and using it on multiple other components:

Because the card component doesn’t have any .html.twig file, it means that this library will only be loaded in, when it is attached to other components.

You could add the card library to any other component by attaching the card library to it.

An example

Twig Created with Sketch.
node--teaser.html.twig
{% extends 'node.html.twig' %}

{% block before %}
  {{ attach_library('my-theme/node--teaser') }}
{% endblock %}

{% block content %}
  {{ attach_library('my-theme/card') }}
  <div class=”card”>
    {{ content }}
  </div>
{% endblock %}

Technically you could add the library wherever you want, but it makes most sense to attach it right before the HTML that will use it, as it then has a visual link by being together in the template.

Sidenote: Don't worry about adding libraries multiple times to the same page. Drupal is smart enough to only load that library once, and at the right time and order!