Theming

Add CSS and JavaScript to a Drupal SDC for Drupal 10, 11

Last updated
Categories
Up-to-date with minor version
11.0.x

One of the benefits of using Drupal single directory components is that Drupal automatically builds and attaches an asset library whenever it is used. Adding CSS styles and JavaScript interactivity to a single directory component (SDC) is as simple as dropping component-name.css and component-name.js files into the root directory of the component. Drupal detects these files, creates an asset library, and attaches it when the component is rendered. This means when you want to add additional CSS or JavaScript assets, you will override the asset library created for your component instead of defining a new one.

In this tutorial, we will:

  • Add component-scoped CSS and JavaScript files.
  • Learn how to override a component's existing asset library to add additional assets.
  • Discuss how to integrate common front-end asset build tools (Gulp, Webpack, Vite, etc.) while working with Drupal single directory components.

By the end of this tutorial, you'll be able to attach CSS and JavaScript assets to an SDC and validate that they load only when the component is in use.

Frontend Theming