Menu Link Attributes is a great Drupal 8 and 9 module that allows you to add attributes to your menu links. Let's see how you can set the attributes programmatically.
Menu link defined statically in a *.links.menu.yml file can be altered with hook menu links discovered alter hook, but if you want to provide a dynamic value you have to use something else.
As of writing this blog post, the Menu Token module for Drupal 8 is still in the alpha version and it might not work in all cases. That's why having an alternative solution is great. The alternative to using the Menu Token module for Drupal 8 is to use Menu link plugins.
Creating a menu link programmatically in Drupal 8 and 9 is easy. You have to provide four values, link title and Uri, menu name for which you want to create a menu link, and optionally you can provide a link weight.
Hierarchical Taxonomy Menu is a Drupal 8 and 9 module for creating menus from taxonomy terms.