How to handle assets in Symfony 4 How to handle assets in Symfony 4 symfony symfony

How to handle assets in Symfony 4


Should images be stored in 'public/images' folder or in 'assets/images'?

Everything in public/ is available through the browser. In here, only production ready and build things should be put.As your images don't need any processing (I assume), you can (should) indeed put the images there.

Now, assume you're needing to do some processing (e.g. ugly JPEG compression), you would put the images in assets/, do some processing and then put only the processed images in public/.

If the images are stored in public/images, will I get any benefit if I pollute the templates with asset('...') calls?

Yes, asset() doesn't have anything to do with Encore or asset build management. The only thing it does is fixing your URLs. This means that if you move your app to sub directories on your server (example.com/app/), the URLs will automatically adapt. Read more about it in the Asset component documentation.


Another good way to reference images with asset() method in Symfony 4 is copying images in public/build when building assets with Encore.

Use copyFiles() in Webpack Encore

Webpack Encore provides a function to copy your images on the public directory to allow asset() to access those files : copyFiles().

In your webpack.config.js

Encore.....copyFiles({        from: './assets/images',        to: 'images/[path][name].[ext]',        pattern: /\.(png|jpg|jpeg)$/    })

Error: Encore.copyFiles is not a recognized property or method.

Please by sure that you are actualy using symfony/webpack-encore-bundle and not symfony/webpack-encore-pack as described here.

composer require symfony/webpack-encore-bundlecomposer remove symfony/webpack-encore-packyarn installyarn upgradeyarn run watch

My package.json

{    "devDependencies": {        "@symfony/webpack-encore": "^0.22.0",        "bootstrap": "^4.1.3",        "node-sass": "^4.10.0",        "sass-loader": "^7.0.1",        "url-loader": "^1.0.1",        "webpack-notifier": "^1.6.0"    },    "license": "UNLICENSED",    "private": true,    "scripts": {        "dev-server": "encore dev-server",        "dev": "encore dev",        "watch": "encore dev --watch",        "build": "encore production --progress"    }}


  1. Edit webpack.config.js after

    Encore .setOutputPath('../build/')

  2. Add the following lines. You can also do more configuration by uncommenting the lines

    .enableVersioning().copyFiles({ from: './assets/images', // optional target path, relative to the output dir to: 'images/[path][name].[ext]', // if versioning is enabled, add the file hash too //to: 'images/[path][name].[hash:8].[ext]', // only copy files matching this pattern //pattern: /\.(png|jpg|jpeg)$/})
  3. Now you can use image by

Source: https://symfony.com/doc/current/frontend/encore/copy-files.htmlDetails: http://toihid.com/?p=332