Vue Webpack Responsive Webp Images with Responsive Loader & 夏普

Vue Webpack Responsive Webp Images with Responsive Loader & Sharp

使用 responsive-loader,我期待对象的 return。相反,我收到一个 base64 字符串,即 data:image/jpeg;base64,bW9kdWxlLmV....

不幸的是,我在其他帖子上找到的几个答案并没有解决我的问题。

Vue 3.2.31,响应式加载器 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 模板

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

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

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

问题是处理 Webpack 的新资产模块。
https://webpack.js.org/guides/asset-modules/

这里是开始编译的Vue3 Webpack配置:

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

要修改,必须用 type: 'javascript/auto' 覆盖 type: 'asset' 以防止资产重复。

使用chainWebpack(在我迄今为止看到的任何文档中均未找到):

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