symfony / webpack-encore

A simple but powerful API for processing & compiling assets built around Webpack
https://symfony.com/doc/current/frontend.html
MIT License
2.23k stars 198 forks source link

Webpack encore + image-webpack-loader webp creation #1105

Open eberhapa opened 2 years ago

eberhapa commented 2 years ago

Hi,

I don't know if it's an encore related issue but I can't create webp images with the image-webpack-loader.

.addLoader({ test: /\.(gif|png|jpe?g|svg)$/i, loader: 'image-webpack-loader', options: { disable: !Encore.isProduction(), webp: { quality: 75 } } })

Everything is working fine but webp images are not created. Does anybody knows how to fix this?

All the best, Patrick

Ambient-Impact commented 2 years ago

I think you need to disable the built-in Encore image rule for that loader you're adding to work. Encore.configureImageRule({enabled: false}) is what you want. I've gotten this to work with that and then adding a loader using ImageMinimizerWebpackPlugin like so:

.addLoader({
  test: /\.(jpe?g|png)$/i,
  loader: ImageMinimizerPlugin.loader,
  enforce: 'pre',
  options: {
    generator: [{
      preset: 'webp',
      implementation: ImageMinimizerPlugin.sharpGenerate,
      options: {
        plugins: ['sharp-webp'],
        encodeOptions: {
          webp: {
            quality: 80,
          },
        },
      },
      // Annoyingly, file URLs that are altered (e.g. PNG to WebP) by this
      // loader appear to incorrectly generate paths using the platform's path
      // separator. This means that if built on Windows, the URLs will use a
      // backslash (\), which is not a path separator in an HTTP URL but rather
      // an escape character, meaning that the URL will be incorrect and a 404.
      filename: function(file) {
        return file.filename.replaceAll('\\', '/');
      },
    }],
  },
})
phucwan91 commented 8 months ago

this configuration worked for me

1.package: yarn add image-webpack-loader --dev 2.in webpack.config.js

.configureImageRule({
        type: 'asset',
        maxSize: 4 * 1024, // use data URI when image size over the maxSize in kb
        // filename: 'images/[name].[hash:8].webp', // for all kind of images
        filename: (module) => {
            return module.filename.match(/\.(png|jpe?g|gif)$/)
                ? 'images/[name].[hash:8].webp'
                : 'images/[name].[hash:8][ext]'
            ;
        },
    },  function(rule) {
        rule.loader = 'image-webpack-loader';
        rule.options = {
            webp: { quality: 75 },
        }
    })
 ;   
carsonbot commented 1 month ago

Thank you for this issue. There has not been a lot of activity here for a while. Has this been resolved?