Add a composer.json file

Last updated on
10 March 2017

If a contributed project maintainer wishes to add a dependency on a packagist library that is not hosted on drupal.org, they can add a composer.json file to their contributed project.

Most contrib developers do not need to do this as long as their drupal.org dependencies are expressed in their .info.ymlfiles.

Define your module as a PHP package

The wider PHP community uses Composer to manage packages; this is also done in Drupal. For example, the Drupal project has a dependency on the "drupal/core" package. The "drupal/core" package has a type defined as "drupal-core" so Composer knows what to do with it. The composer/installers library defines a number of Drupal types. These are

  • drupal-module
  • drupal-theme
  • drupal-library
  • drupal-profile
  • drupal-drush

Here is a full example of how the mobile_detect project uses composer.json to depend on the external project mobiledetect/mobiledetectlib:

{
    "name": "drupal/mobile_detect",
    "description": "Mobile_Detect is a lightweight PHP class for detecting mobile devices.",
    "type": "drupal-module",
    "homepage": "https://drupal.org/project/mobile_detect",
    "authors": [
        {
            "name": "Matthew Donadio (mpdonadio)",
            "homepage": "https://www.drupal.org/u/mpdonadio",
            "role": "Maintainer"
        },
        {
            "name": "Darryl Norris (darol100)",
            "email": "admin@darrylnorris.com",
            "homepage": "https://www.drupal.org/u/darol100",
            "role": "Co-maintainer"
        }
    ],
    "support": {
        "issues": "https://drupal.org/project/issues/mobile_detect",
        "irc": "irc://irc.freenode.org/drupal-contribute",
        "source": "https://cgit.drupalcode.org/mobile_detect"
    },
    "license": "GPL-2.0+",
    "minimum-stability": "dev",
    "require": {
        "mobiledetect/mobiledetectlib": "~2.8"
    }
}

For naming your package, you must follow Drupal's Composer package naming conventions.

Defining dependencies in composer.json

You may optionally define external dependencies for your module in composer.json. Drupal core will not automatically discover or manage these dependencies. To utilize dependencies defined in a project's composer.json file, you must use one of the following maintenance strategies:

For more information on composer as a dependency manager for Drupal, review a comparison of Composer and Drush Make as dependency managers.