Manage & Install Patches with Composer in Drupal

When setting up a Drupal site, I've often come across contributed modules or core Drupal code that requires patches. Previously I would download the patch to the module or source directory and:

cd /path/to/MODULENAME

patch -p1 < patchfile.patch

But now, using composer, these steps will ensure that a patch isn't missed or overwritten each time composer update or composer install is run. Instead the patch is automatically applied each time.

First, install cweagans/composer-patches with composer. Navigate to your project directory:

composer require cweagans/composer-patches

Now we are going to manually edit the composer.json file to allow it to find our patches located in a new composer file named "composer.patches.json."

1. Create the composer.patches.json file and open it in a text editor.

touch composer.patches.json
coda composer.patches.json

The file contents should look like this:

{
  "patches": {
	  
  }
}

So, for example, one patch used to prevent some buggy behavior in the Layout Builder module in Drupal core.

{
  "patches": {
    "drupal/drupal": {
        "Layout Builder unable to save": "https://www.drupal.org/files/issues/2019-12-28/layout-builder-save-issue-3045171-120.patch"
      }
  }
}

Now we have to tell the composer.json file where our patches file is and enable patching.

Open composer.json and edit the section starting with "extra": {

    "extra": {
        "drupal-scaffold": {
            "locations": {
                "web-root": "web/"
            }
        },

and make it look like this:

"extra": {
        "patches-file": "composer.patches.json",
        "enable-patching": true,
        "drupal-scaffold": {
            "locations": {
                "web-root": "web/"
		}
        },

After saving, we run composer update:

composer update

The output should indicate that the patch file was recognized. Something like:

Removing package drupal/mymodule so that it can be re-installed and re-patched.
  - Removing drupal/mymodule (dev-1.x)
Deleting web/modules/contrib/mymodule - deleted
Loading composer repositories with package information
Updating dependencies (including require-dev)

 

Article references

Add new comment

comment editor

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type='1 A I'> <li> <dl> <dt> <dd> <h2 id='jump-*'> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.