How to integrate Webpack Encore in Symfony for asset management?

  1. Install Webpack Encore by running the following command in your Symfony project directory:
yarn add @symfony/webpack-encore --dev
  1. Configure Webpack Encore by creating a webpack.config.js file in the root of your project directory. Here is an example configuration:
// webpack.config.js const Encore = require('@symfony/webpack-encore'); Encore .setOutputPath('public/build/') .setPublicPath('/build') .addEntry('app', './assets/js/app.js') .enableSingleRuntimeChunk() .cleanupOutputBeforeBuild() .enableBuildNotifications() .enableSourceMaps(!Encore.isProduction()) .enableVersioning(Encore.isProduction()) ; module.exports = Encore.getWebpackConfig();
  1. Update your Symfony application to use Webpack Encore for asset management by including the following code in your base template:
<!DOCTYPE html> <html> <head> {# CSS assets #} {% block stylesheets %} {{ encore_entry_link_tags('app') }} {% endblock %} </head> <body> {# JavaScript assets #} {% block javascripts %} {{ encore_entry_script_tags('app') }} {% endblock %} </body> </html>
  1. Compile your assets by running the following command:
yarn encore dev
  1. You can also use the production environment by running:
yarn encore production

Your assets will be compiled and stored in the public/build directory. You can now easily manage and optimize your frontend assets using Webpack Encore in your Symfony project.