4

In Drupal 8 some JavaScript changes were introduced: All JavaScript scripts should be defined using hook_library_info() and added to the page only with #attached attribute of the render array.

What should I do to define external libraries? Should I create a libraries directory and upload the library there, or should they be managed by the module using Composer?

0

1 Answer 1

3

Since you posted this question, hook_library_info was replaced with *.libraries.yml files.

An example of a simple library declaration looks like this:

jquery.form:
  remote: https://github.com/malsup/form
  version: 3.39
  js:
    assets/vendor/jquery-form/jquery.form.js: {}
  dependencies:
    - core/jquery
    - core/jquery.cookie

Once declared, this library can be attached to a render array like this:

$element['#attached']['library'][] = 'core/jquery.form';

Now Drupal should take care of adding the library and all required dependencies to the page. Even though the library declaration can contain a remote url, Drupal will not automatically download the library for you.

If I'm not mistaken, you will always need a module or a theme with a .libraries.yml file to act as the provider of your library. However a module can be really simple, you only need a .info.yml file to declare a module.

3
  • 1
    The last bit's not totally true, you can also use it in a theme...
    – Clive
    Apr 3, 2014 at 21:45
  • 1
    Thanks Clive, you're completely right. It was so obvious to me that I forgot to mention it :-) I updated the answer. Apr 3, 2014 at 22:03
  • 1
    I used this answer to draft documentation on drupal.org: drupal.org/node/2216195
    – batigolix
    Oct 9, 2014 at 15:03

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.