[SOLVED] How to include third party libraries in Drupal 8 for custom modules?

May 09, 2016 - 07:42

In Drupal 8, third party libraries are downloaded and managed via composer. In each Drupal project there must be only one vendor folder. Composer Manager allows a single vendor/directory shared across all modules which prevent code duplication and version mismatches. This is done by merging the requirements of all modules found, into the consolidated composer.json file. In a custom module, set the dependency for composer manager module in .info file.

dependencies:
  - composer_manager

Write composer.json file for your custom module to download php library dependency. Your composer.json file should contain at least name and requirement (your php library).

{   
  "name": "drupal/mymodule",
  "require": {
    "endroid/qrcode": "^1.6"
  }
}

Following are the steps to manage custom modules with composer.json :
1. First of all install Composer Manager module.
2. In your Drupal root directory, run the module's init.php script on the command line. For example,

username@locahost:/var/www/SITENAME$ php modules/contrib/composer_manager/scripts/init.php
3. In command line, you will see the message after step(2) 'Composer Manager has been successfully initialized'. Now run composer drupal-update from the root of your Drupal site directory. For example,
username@locahost:/var/www/SITENAME$ composer drupal-update
composer update

After the above three steps, the php library is downloaded to the vendor folder in Drupal root directory. Now you can see the composer manager module status in /admin/reports/composer. If you want to download dependency library in the specified folder path, then set path in your composer.json file.

"config": {
  "vendor-dir": "includes"
}