Change record status: 
Project: 
Introduced in branch: 
8.9.x
Introduced in version: 
8.9.0
Description: 

In Drupal 8, contrib modules use the Libraries module to allow project to store third party libraries in different locations. There locations are:

  • PATH/TO/SITE/libraries (for example sites/example.com)
  • libraries
  • PATH/TO/INSTALL_PROFILE/libraries

This functionality has been move to Drupal core and now libraries with locations starting with /libraries/ can be in any of these locations. They are searched in the order above and the first match found is used.

Here's an example libraries declaration:

dropzonejs:
  title: 'Dropzonejs'
  website: http://www.dropzonejs.com
  version: 4.0.1
  license:
    name: MIT
    url: https://github.com/enyo/dropzone/blob/master/LICENSE
    gpl-compatible: true
  js:
    /libraries/dropzone/dist/min/dropzone.min.js: {}
  css:
    component:
      /libraries/dropzone/dist/min/dropzone.min.css: {}

Additionally, core provides \Drupal::service('library.libraries_directory_file_finder')->find() which is the equivalent of the libraries_get_path() function.

Before

$exif_path = libraries_get_path('exif-js') . '/exif.js';

After

$library_file_finder = \Drupal::service('library.libraries_directory_file_finder')->find('exif-js/exif.js');

Modules may also use the following pattern to avoid a dependency on Drupal 8.9 and conditionally support it while also keeping optional support for the libraries module with the following pattern. This can later be simplified to just the call to the new API once the supported core version is 8.9 or higher.

if (\Drupal::hasService('library.libraries_directory_file_finder')) {
  $exif_path = \Drupal::service('library.libraries_directory_file_finder')->find('exif-js/exif.js');
}
elseif (\Drupal::moduleHandler()->moduleExists('libraries')) {
  $exif_path = libraries_get_path('exif-js') . '/exif.js';
}
else {
  $exif_path = DRUPAL_ROOT . '/libraries/exif-js/exif.js';
}
Impacts: 
Module developers
Themers
Distribution developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done

Comments

ccjjmartin’s picture

FYI, this change record hit the drupal8changes twitter account so it will probably get some traffic today and in days following.

I think it would be helpful for others if the examples related to each other. Right now I am seeing one example for dropzone js and another for exif js.

The main question I have is if the js files live in a sub-directory like in the dropzone js example would the new code look like?

$library_file_finder = \Drupal::service('library.libraries_directory_file_finder')->find('dropzone/dist/min/dropzone.min.js');

Thanks in advance.