4

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?

poldixd
  • 1,103
  • 2
  • 13
  • 27

3 Answers3

6

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">
poldixd
  • 1,103
  • 2
  • 13
  • 27
4

If you don't want to rely on webpack for responsively loading images, you may want to try this nuxt module: https://github.com/reallifedigital/nuxt-image-loader-module

The downside to this module is that it doesn't currently support srcset natively and requires a local installation of the Graphicsmagick library. The upside is that anything that's available in Graphicsmagick (image manipulation wise) can be used to process your images. Also, you can implement your own image srcset from following the instructions and implementing your image tag like this:

<img src="image.png" srcset="image-1x.png?style=1x 1x, image-2x.png?style=2x 2x alt="" />

You should be able to implement any responsive image this way.

For our responsive views in nuxt, such as a 'feed' of latest content, we wanted to use smaller images from what was being used on the main articles, so this module does exactly what we need it to.

Disclosure: I wrote this module to solve our particular responsive requirement which, given the original poster's description, sounds like there's a lot of overlap.

3

It's not a task for Nuxt, but for Webpack.

You have to install a webpack loader to resize your images on build task and that will inject the srcSet in your html generated from Nuxt.js

eg. responsive-loader https://github.com/herrstucki/responsive-loader

About Nuxt.js & webpack configuration: https://nuxtjs.org/faq/extend-webpack

Nicolas Pennec
  • 7,533
  • 29
  • 43