I desire to add two files, one for CSS, one for JS, to be used in my application globally (without being dependent in any theme; contrib or core); I can add these with Bash (permissions changed to prevent deletion in Drupal upgrades):

touch /var/www/html/example.com/{css.css,js.js}
chmod 644 /var/www/html/example.com/{css.css,js.js}

I can't have either file without the other; I must have a single solution to include both files.

Why

Sometimes I create small sites without modifying the theme at all but I still need some minor CSS/JS changes that IMO doesn't justify creating a subtheme, directory hierarchy, etc so I wouldn't mind creating two "quick" and "global" files directly on the Drupal app root just for that.

My question

Can this be done in Drupal 8.5.6?

closed as off-topic by leymannx, Kevin, Felix Eve, mradcliffe, Alfred Armstrong Sep 21 at 10:06

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions on programming, PHP, SQL, etc. that do not relate directly to Drupal are off-topic here, but can be asked on Stack Overflow." – leymannx, Kevin, Felix Eve
If this question can be reworded to fit the rules in the help center, please edit the question.

up vote 3 down vote accepted

Add a module, give it a libraries file (MODULE.libraries.yml):

global:
  js:
    /js.js: {}
  css:
    theme:
      /css.css: {}

In the .module file, implement hook_page_attachments:

function MODULE_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'MODULE/global';
}

When you enable the module (or clear cache if it's an existing module), the CSS and JS will be included on every page.

  • 1
    As I said above, every solution I can think of is considerably more complicated than the code in the answer. Drush can't help with this, not in any way that wouldn't involve writing plenty more PHP to extend it. The module guide might seem daunting but you just need a MODULE.info.yml file with name, type and core key/values in it, add a MODULE.libraries.yml with the code in the answer, a MODULE.module file with the same (replacing all occurrences of MODULE with the machine name of your module). After that enable the module and you're done – Clive Sep 6 at 22:56
  • Oh yeah drush can do that, just drush en module_machine_name after you copy the folder into docroot/modules (or docroot/modules/custom) – Clive Sep 6 at 22:58
  • Sorry but as the question was answered, and could be useful to future visitors, it's too late to change it now. You can always ask a new question, but please make sure to frame it properly (as in don't direct it specifically at me, make sure the problem is well explained, etc) – Clive Sep 7 at 11:42

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