Home > other >  Vue Webpack Responsive Webp Images with Responsive Loader & Sharp
Vue Webpack Responsive Webp Images with Responsive Loader & Sharp

Time:03-31

Using responsive-loader, I am expecting the return of an object. Instead, I am receiving a base64 string, i.e. data:image/jpeg;base64,bW9kdWxlLmV....

Unfortunately, the few answers I've found on other posts have not resolved my issue.

Vue 3.2.31, Responsive Loader 2.3.0, Sharp 0.30.3

vue.config.js

const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const ResponsiveLoaderSharp = require('responsive-loader/sharp')

module.exports = {
    chainWebpack: config => {
        config.plugin('polyfills').use(NodePolyfillPlugin)

        config.module
            .rule('images')
            .use('url-loader')
            .loader('responsive-loader')
            .options({
                adapter: ResponsiveLoaderSharp,
                name: 'img/[name]-[width].[hash:8].[ext]',
                format: 'webp',
                quality: 60,
                sizes: [320, 640, 960, 1200],
            })
    },
}

Vue Template

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
    setup(){
        const myImage = require('@/assets/my-image.jpg')

        console.log(myImage)
    }
})
</script>

CodePudding user response:

The issue was dealing with Webpack's new asset modules.
https://webpack.js.org/guides/asset-modules/

Here is the starting compiled Vue3 Webpack configuration:

      /* config.module.rule('images') */
      {
        test: /\.(png|jpe?g|gif|webp|avif)(\?.*)?$/,
        type: 'asset',
        generator: {
          filename: 'img/[name].[hash:8][ext]'
        }
      },

To modify, type: 'asset' must be overridden with type: 'javascript/auto' to prevent asset duplication.

Using chainWebpack (not found in any documentation I've seen to date):

config.module
    .rule('images')
    .type('javascript/auto')
    .use('responsive')
    .loader('responsive-loader')
    .options({
        adapter: require('responsive-loader/sharp'),
        format: 'webp',
    })
  • Related