Drupal 8 add javascript and pass data in a hook with custom module I am building a custom module with Drupal 8. One of the requirements of the module is that it sets up a javascript file based on the configuration settings, which the user of the module sets up in module configuration. 

The javascript which needs to be added to the page depends on the configuration settings. Hence I can not add it using Libraries as mentioned in this article: Adding assets to Drupal module.

I first implemented it using a block. I use Twig templates to pass the configuration variables in PHP to the twig file, and in the twig file, I have a &lt;script&gt; tag to add the javascript based on the config variables. Refer Using twig templates. 

The problem with this approach is that user needs to add the block on the page, and there is no UI facing element on that block. I also find it very messy. 

Is there a cleaner way to add my javascript using hook and pass variables to it? I looked around and found hook_install and hook_page_attachments. So I can add Javascript, but don't know how I can pass any php variables to it. 

I am new to Drupal development. Any help with this is really appreciated. 

TL;DR I need to find a way to add Javascript using Drupal hook and pass some PHP variables to it.
You can add variables into the scope without generating a Javascript file and then use a hook like preprocess_html to add them in:

$variables['#attached']['drupalSettings']['mymodule']['config']['color'] = $config-&gt;get('mymodule.color');


These value(s) are then available in the drupalSettings scope, which you can read out in your module Javascript file in order to do things. Just pass drupalSettings into it.