I am building an application with Symfony 4
and I'd like to follow the best practices for web assets. I use Encore/Webpack for SCSS and JS and it works well; the resulting JS+CSS are nicely stored in /public/build folder. I'm stuck at how to store and use static assets like images, movies, sounds.
Should images be stored in 'public/images' folder or in 'assets/images'?
And some followup questions:
If the images are stored in public/images
, will I get any benefit if I pollute the templates with asset('...')
calls?
If the images are stored in assets/images
, then:
public/images
to be served via http? ./bin/console assets:install
did nothing, saying: '[OK] No assets were provided by any bundle.'.Regards,
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.
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)$/
})
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-bundle
composer remove symfony/webpack-encore-pack
yarn install
yarn upgrade
yarn 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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With