With Composer we can require PHP dependencies for our modules. What's the right way to include third party dependencies such as a jQuery plugin into a module?
1 Answer
There are a couple of ways you can do it. One way is to define a remote JS resource in your libraries.yml.
See the "CDN/Externally hosted" section here: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
I do this for AddThis (which can be done at the theme or module level) and Fontkit. This is an approach you can take with jQuery plugins that are available via CDN. As long as that resource is available, all you have to do is attach it when needed.
For Javascript that has no external hosting, like CKEditor plugins, I write in the README to download the plugin to libraries/(plugin name) of the docroot
. There is no way, that I know of yet, to automate that process. This also requires writing into hook_requirements
in the install file of the module to check that the file exists on the server before installing.
Another way, you could have composer do a bower install
or npm install
:
Though, it would require the user to have all of those tools installed, and to be a composer user. One gap for that right now is if someone grabs the tarball off drupal.org or uses drush to get your module, none of that would work and they'd still be missing packages. Pathing could also be a headache when trying to write these commands to work for everyone, as well. Composer usage hasn't gained as much traction yet as it needs to beyond developers, but it will become more important moving forward. For example, modules requiring PHP packages (like Search API) simply cannot be drush installed or downloaded from drupal.org and manually placed - a method many, many site builders still use.
Others would say to just stick it in your module, but unless you wrote the plugin, that is against the Drupal licensing/contrib guidelines regarding third party code.
-
You can also provide the user with a CDN (first option) and allow them to override it with a downloaded library. Some users might not want to (or can) use CDNs.– EyalCommented Dec 17, 2016 at 21:51