How to solve Magento 2 var/generation cannot be deleted problem

Magento 2 import export debug log

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.

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:

While it affects your store as expected in development mode, you may get the following error message on the production system:

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:

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:

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: Magento 2 var/generation cannot be deleted warning.