Module Development

Add CSS and JavaScript to a Module's Output for Drupal 8, 9, 10, and 11

Modules can define new asset libraries that include CSS and JavaScript files, and then attach them to the content they output. This process involves defining a new asset library, authoring the related CSS and JavaScript, and using the #attached render array property to associate the library with the applicable content.

In this tutorial, we'll:

  • Define a new asset library in the anytown module.
  • Include CSS and JavaScript in the library.
  • Attach the new library to the /weather page.

By the end of this tutorial, you should be able to define an asset library and add CSS and JavaScript to a page from a Drupal module.

Drupal Module Developer Guide