The best practice for composer dependencies is to keep them ignored in VCS. On some rare occasions, you may need to keep them there. So, how to do it correctly?
You most likely are using git as VCS. When installing composer dependencies, sometimes the composer will install some dependencies from git by cloning the repository, which will cause problems that are hard to see - you committed everything. It works, but it does not work in a different environment. The most likely cause is that the dependencies cloned from git, have their .git
folder and git does not want to include them.
How to fix this? You may delete .git folders manually, which is error-prone, easy to miss, and forget to do. Because we use composer, we could add a custom script that will do that automatically - create a custom PHP class that has a static method, which calls a special command to find all .git
folders and delete them. Then include it in the composer.json
file in post-install and post-update hooks which will trigger cleanup when installing or updating dependencies.
<?php
namespace MyProject\composer;
/**
* Custom composer scripts for the project.
*/
class ScriptHandler {
/**
* Removes .git folders from codebase.
*
* All code dependencies are added into git, but .git folders in some
* dependencies may cause issues, so it is best to remove them.
*/
public static function removeGitDirectories(): void {
$drupalRoot = getcwd() . '/web';
exec("find " . $drupalRoot . "/../vendor -name '.git' | xargs rm -rf");
exec("find " . $drupalRoot . "/libraries -name '.git' | xargs rm -rf");
exec("find " . $drupalRoot . "/modules/contrib -name '.git' | xargs rm -rf");
exec("find " . $drupalRoot . "/themes/contrib -name '.git' | xargs rm -rf");
}
}
{
// .....
"scripts": {
"post-install-cmd": [
"MyProject\\composer\\ScriptHandler::removeGitDirectories"
],
"post-update-cmd": [
"MyProject\\composer\\ScriptHandler::removeGitDirectories"
]
}
// .....
}
You may need to modify the command if you are not using bash or a similar shell, use ChatGPT or a similar AI tool if you don't know how to do it.
The only side effect is that sometimes the composer will tell you that the .git
folder is missing - you can continue just fine. I can say that things have been working for years. I still recommend keeping them outside VCS, but I know sometimes there are valid reasons for the opposite.