Symfony Webpack/Encore processing unreferenced source images

Viewed 693

I am attempting to get Webpack to process and copy all the image files in src folder and output them to the build folder using ‘image-webpack-loader`.

As far as I understand, Webpack will only do this with images referenced in CSS/SASS/LESS or an entry point.

I am working on a Symfony project and have many references in twig templates, which are obviously ignored.

Any idea how I could make this happen without the addition of a build tool or making a duplicate reference file for every image that I include in a project template?

2 Answers
  1. Create a s subdirectory under web root:

    Symfony 3:

    web/s
    

    Symfony 4 & 5:

    public/s
    
  2. Configure your new subdomain:

    Symfony 3: (app/config/config.yml)

    framework:
        assets:
            base_urls:
                - '%protocol%://s.%host%'
    

    Symfony 4 & 5: (config/packages/assets.yaml)

    framework:
        assets:
            base_urls:
                - '%protocol%://s.%host%'
    

    Note:

    1. %protocol% is either http or https accoring to you environment
    2. %host% is your host, maybe example.com or something.
  3. Configure Webpack (webpack.config.js)

    Symfony 3:

    var Encore = require('@symfony/webpack-encore');
    
    Encore
        // ...
        .setOutputPath('./web/s/build/')
        .setPublicPath('/build')
        .setManifestKeyPrefix('build')
        .cleanupOutputBeforeBuild()
        // ...
    ;
    
    module.exports = Encore.getWebpackConfig();
    

    Symfony 4 & 5:

    var Encore = require('@symfony/webpack-encore');
    
    Encore
        // ...
        .setOutputPath('./public/s/build/')
        .setPublicPath('/build')
        .setManifestKeyPrefix('build')
        .cleanupOutputBeforeBuild()
        // ...
    ;
    
    module.exports = Encore.getWebpackConfig();
    
  4. Put all your images inside /web/s or /public/s according to your Symfony version.

  5. Inside your Twig views, access them like below:

    <img src="{{ asset('photo.jpg') }}" alt="Photo"/>
    
  6. Accept and hit upvote on this cool answer!

In webpack.config.js, you could add .copyFiles() to the Encore object. This will take an object with "from", and "to" keys, with a couple of wildcards.

Here is an example:

.copyFiles({
    from: 'src',
    to: 'images/[path][name].[ext]'
})  
Related