4

In my libraries.yml file, I have something like this, being used to define "foo-bar" as a library that can be pulled in from various parts of the site:

foo-bar:
  version: 0.0.x
  js:
    js/foo-dev.js: {}

This works well on my local environment, but on our production and QA environments, I would like for it to look more like this:

foo-bar:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

(The prod version will include optimizations that normally don't appear with minification alone).

Currently, we are using the sites/<site>/settings.*.php files and the config-split module to have different configurations based on the environment, but is there a way to have the foo-bar library reference the dev-friendly version on one environment, and the production version on all others?

1

1 Answer 1

4

Look at hook_page_attachments. In the sample snippet provided behind that link there is a simple if-request which attaches a certain library only when a certain condition is met. Do the same.

MYTHEME/MYMODULE.libraries.yml

foo-bar-dev:
  version: 0.0.x
  js:
    js/foo-dev.js: {}
foo-bar-prod:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

MYTHEME.theme/MYMODULE.module

function MYTHEME/MYMODULE_page_attachments(array &$attachments) {

  // Conditionally attach an asset to the page.
  if (\Drupal::request()->getHost() == 'example.com') {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-prod';
  }
  else {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-dev';
  }
}

More info on base URL: how to get base url of a site?.

3
  • 1
    If you have attached the library already in other places and therefore want to keep the library name you could use hook_library_info_alter to alter only the js file name.
    – 4uk4
    Commented Aug 14, 2018 at 21:07
  • @4k4 – Gosh, you are so right. Found my own question when googling named hook: drupal.stackexchange.com/q/210959/15055
    – leymannx
    Commented Aug 14, 2018 at 21:09
  • 1
    As noted here if you want to put this logic in a theme, you cannot use hook_page_attachments() but can use hook_page_attachments_alter or hook_preprocess_page. Commented Oct 17, 2019 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.