How to use a third party JavaScript library in a Drupal theme?

2019. Jan. 2. · 1 min read
In a recent project I wanted to use the Tippy.js library in the custom Drupal 8 theme I was working on. While I knew most of the things needed to do this in theory I did not know how I should do it step by step in practice.

Unfortunately, I did not find one resource which would have told me what to do. But I found several different resources with partial information and by using them I was able to figure out a working solution. Here it is:

  1. Add the third-party JS lib to your theme.

    You can use your favorite package manager / build tool or simply copy the lib into (a folder like “vendor” in) your custom theme. (You could use an external CDN as well but it is not recommended.)

  2. Create your custom JavaScript file which configures the behavior / usage of the lib.

    I built a component-based theme (using Emulsify from Four Kitchens) so I created my file in a component folder.

  3. Add both the lib and your custom JS file separately to your theme’s libraries.yml and set the lib as a dependency of your custom JS.

    You can reference the lib as dependency using your theme’s machine name and the name you use for it in the libraries file (eg. “mytheme/tippy”). Something like this:

        vendor/tippy.all.min.js: {}
        components/_patterns/03-organisms/twist/twist.js: {}
        - mytheme/tippy
  4. Make your theme use your custom JS library.

    There are several ways to do it. I used the attach_library() function in the Twig template of my component:

    {{ attach_library('mytheme/twist') }}

And that’s all. Happy Drupal theming!