Use composer.json file in custom module to install dependent vendor packages

Like contributed modules, dependencies of a custom module can also be installed by providing a composer.json file in the directory of the custom module. This provides a neat solution to ensure that external libraries/modules are available in the correct place, without overloading the root (projects) composer.json file. Note, that dependencies to other Drupal modules (either contributed or custom) still have to be defined in the .info.yml file in order for them to be enabled.

Assuming your Drupal project is based on the drupal/recommended-project Composer template, the only thing you have to do is to extend the "repositories" section of your main/root composer.json file with the path where your custom modules are located:

...
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "path",
            "url": "web/modules/custom/*"
        }
    ],
...

In your custom module, you can add a composer.json file and instruct to install all needed libraries. For instance:

{
    "name": "drupal/custom_module",
    "description": "An example composer.json file for a custom module.",
    "type": "drupal-custom-module",
    "authors": [
        {
            "name": "dr. Niels Sluijs",
            "email": "niels@sicse.dev"
        }
    ],
    "require": {
        "drupal/examples": "^1.0",
        "other/library": "^9.0"
    },
    "extra": {
        "patches": {
            "drupal/examples": {
                "When using cweagans/composer-patches even patches for dependencies can be defined here": "url-or-path-to-the-patch"
            }
        }
    }
}

All you have to do now, is to include your custom module in your main/root composer.json file by invoking the command composer require drupal/custom_module:@dev.

In the example above, we have added an "extra" section to indicate which patches to apply on the installed dependencies. This functionality is provided by the cweagans/composer-patches library, which should (is recommended) to be installed/required in the main/root composer.json file. For this to work, you have to indicate in the main/root composer.json file that patches of dependencies are allowed:

...
    "extra": {
        ...
        "enable-patching": true,
        ...
    }
...

Note that above solution doesn't use the wikimedia/composer-merge-plugin, which use has been deprecated for Drupal core.

Category
Drupal
Composer