Sun, 22 Sep 2019

A Simple Solution for Removing Assetic from Symfony 3/4

Finding the answer to this specific question didn't return exactly what I needed, so when that happens, I typically write a blog to help those out in similar situations.

After you resolve all of the deprecations in preparation to upgrade to Symfony 4 is that composer might complain that "Package symfony/assetic-bundle is abandoned, you should avoid using it. Use symfony/webpack-encore-pack instead."

Googling this topic brings up lots of resources about why its deprecated, and you might even be tempted to use something like maba/webpack-migration-bundle. Except that a few composer dependencies got in my way, so rather than grapple with composer dependencies, I found a simpler way to go, and thought I'd share if your situation is similar enough to mine.

At a high level, the three steps that my approach takes is to eliminate the dependencies on Assetic by configuring your styles/javascript configurations manually, then to remove dependencies on Assetic, then migrate your configurations to whatever you prefer (e.g. Encore, if you like). The insight to first remove the Assetic dependency, then migrate to something else didn't strike me at first, so that's essentially the "light bulb idea" here.

Here are (marginally) more detailed steps:

  1. I first scanned my twig files to see what kind of dependencies I was dealing with. A unix command like the following might be useful, make sure to specify less/sass in the grep as your situation warrants:
    find app/Resources/ -name "*.twig" | xargs egrep '/js|css/'
  2. Then I scanned my src files to see if any "use Assetic" strings exist in my project using a similar find/xargs command. Finding none, I knew I had a largely twig-centric configuration that would respond well to my approach.
  3. The next step is to convert anything that looks like php {% stylesheets } and {% javascripts } into basic HTML equivalents.
  4. The final step is removing the configuration settings from the Symfony configuration. Namely, Assetic references in composer.json, AppKernel.php and config.yml. (Remove the reference to AsseticBundle() in AppKernel.php, the Assetic block in config.yml, and the assetic reference in composer.json)
  5. Test your changes (clear cache on the server, and your browser), and when you're ready, commit your changes, and determine your next steps for how to handle the complexity you just manually re-created. With this commit diff in hand, you should have a list of stylesheets and js files that may need another commit to introduce Encore or whatever else you prefer.

Given this is effectively reversing the directions for implementing Assetic it should be an effective way of rolling it back, particularly if you haven't pulled every trick out of the Assetic toolbox. Docs for Symfony 4 outline how to use Encore, should that suit your needs better than static configuration.

Khan Klatt

Khan Klatt's photo