How to solve Magento 2 var/generation cannot be deleted problem
You might have already faced the var/generation cannot be deleted warning while setting up a new Magento 2 shop. However, this problem is not serious, and you can easily fix it with almost zero effort. In the following article, we shed light on the solution of the Magento 2 ‘var/generation cannot be deleted’ issue. You can find more tips here: Magento 2 Developer’s Cookbook.
Table of contents
Magento 2 ‘var/generation cannot be deleted’ problem
Let’s imagine a situation when you have to add a new module or change some injections of the already existing ones. Although your e-commerce website is in production mode, you may use a terminal applying the following command:
1 |
php bin/magento setup:di:compile |
While it affects your store as expected in development mode, you may get the following error message on the production system:
1 2 3 4 5 6 7 8 9 |
The directory "/path_to_project/var/generation" cannot be deleted Warning!rmdir(/path_to_project/var/generation): Directory not empty#0 /path_to_project/setup/src/Magento/Setup/Console/CompilerPreparation.php(68): Magento\Framework\Filesystem\Driver\File->deleteDirectory('/path_to_project/...') #1 /path_to_project/vendor/magento/framework/Console/Cli.php(74): Magento\Setup\Console\CompilerPreparation->handleCompilerEnvironment() #2 /path_to_project/bin/magento(22): Magento\Framework\Console\Cli->__construct('Magento CLI') #3 {main} PHP Fatal error: Uncaught Error: Class 'Cli' not found in /path_to_project/bin/magento:31 Stack trace: #0 {main} thrown in /path_to_project/bin/magento on line 31 |
Possible issues
Some inexperienced developer developers try to solve the problem like it is a file permission issue. They try to change file permissions to delete the var/generation folder completely. However, this approach leads to an error on a storefront. At the same time, it also increases security risks. So, how to act properly?
How to solve Magento 2 ‘var/generation cannot be deleted’ problem
The solution of the ‘var/generation cannot be deleted’ problem is quite simple. You have to do a simple static deploy before you run the compilation. Use this command:
1 |
php bin/magento setup:static-content:deploy |
Now, when static-content deploy is finished, you can compile your modules. This procedure will no longer cause the error.
How to solve Magento 2 ‘var/generation cannot be deleted’ problem for multilingual sites
If your store is not in English, declare a language for the static deploy command. For instance, you can the following one for a German shop:
1 |
php bin/magento setup:static-content:deploy en_US de_DE |
As you can see, you have to include en_US and then add de_DE, since there are lots of strings in English on both frontend and backend.
Conclusion
Now, you know the easiest way of solving the ‘var/generation cannot be deleted’ issue. For further information, follow this link: