配置 Vue loader 和 lazysizes 以使用 Nuxt 转换 url

Configure Vue loader and lazysizes to transform urls with Nuxt

我正在尝试使用 Nuxt 配置 lazysizes,但 Webpack 不处理我的 url,所以我收到 404 错误。我得到路径 src="~/assets/img.png" 而不是 src="/_nuxt/assets/img.png"。我将 lazysizes 添加为 npm 包,并将以下内容添加到我的 nuxt.config.js 文件中。

   /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    '~/plugins/lazysizes.client.ts',
  ],
  /*
   ** Build configuration
   */
  build: {
    extend(_config, { isClient, loaders: { vue } }) {
      // Extend only webpack config for client-bundle
      if (isClient) {
        vue.transformAssetUrls.img = ['src', 'data-src']
      }
    },
  },

并将此内容添加到plugins/lazysizes.client.ts

import lazySizes from 'lazysizes'
export default lazySizes

为了尽量减少复制,我只使用像这样的非常简单的图像。

<img
  class="lazyload"
  data-src="~/assets/img.png"
  alt="Image description"
  loading="lazy"
/>

我完成了这篇文章 https://dev.to/ignore_you/minify-generate-webp-and-lazyload-images-in-your-vue-nuxt-application-1ilm

找到答案了!如果有人来这里,为了将来参考,我阅读这篇文章解决了它https://medium.com/@dannjb/a-lazy-loading-image-component-for-nuxt-js-c34e0909e6e1

As I run SSR using yarn generate, I need the asset url transform to happen on the server too; the isClient check is removed.

移除 SSR 的 isClient 检查后,我让它工作了!