Search code examples
image-resizingnuxt.js

How to resize images for different responsive views?


I created a site with nuxt.js and bootstrap. For the responsive views i need to create different image sizes. Nuxt.js can't resize images. How do you do this?


Solution

  • Now I have the solution. Install responsive-loader and sharp.

    Modify the nuxt.config.js and add the code under build: {}:

    build: {
      /*
      ** Run ESLint on save
      */
      extend (config, { isDev, isClient }) {
    
        // Default block
        if (isDev && isClient) {
          config.module.rules.push({
            enforce: 'pre',
            test: /\.(js|vue)$/,
            loader: 'eslint-loader',
            exclude: /(node_modules)/
          })
        }
        // Default block end
    
    
        // here I tell webpack not to include jpgs and pngs
        // as base64 as an inline image
        config.module.rules.find(
          rule => rule.loader === "url-loader"
        ).exclude = /\.(jpe?g|png)$/;
    
        // now i configure the responsive-loader
        config.module.rules.push({
            test: /\.(jpe?g|png)$/i,
            loader: 'responsive-loader',
            options: {
                min: 575,
                max: 1140,
                steps: 7,
                placeholder: false,
                quality: 60,
                adapter: require("responsive-loader/sharp")
            }
        })
    
      }
    }
    

    Now you can use the following code to display images

    <img :src="require('~/assets/images/Foo.jpg?size=400')" :srcset="require('~/assets/images/Foo.jpg').srcSet">