How can I use a custom module to add JS to every page with Drupal 8?
I've found lots of example scattered over the internet that maybe used to work but no longer work.
Assume the custom module is called example.
First create a example.libraries.yml file in your module root folder like this:
example:
version: 1
js:
example.js: {}
dependencies:
- core/jquery
Next in example.module use hook_page_attachments()
too add your JS to every page:
/**
* Implements hook_page_attachments().
*/
function example_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'example/example';
}
So now the custom module has 4 files:
hook_page_build()
and hook_page_alter()
are now deprecated so can no longer use them.
There is a page drupal.org on adding CSS and JS using a custom module with more information.
$attachments['#attached']['library'][] = 'example/example';
shouldn't the first example be the theme name?
Commented
Apr 13, 2016 at 1:10