Code Monkey home page Code Monkey logo

sharp-loader's Introduction

sharp-loader

Use sharp to automatically generate image assets with webpack.

build status coverage license version downloads

Usage

IMPORTANT: You need to have vips installed for sharp to work. The sharp npm module may attempt to do this for you, it may not.

npm install --save sharp-loader sharp

NOTE: If your configuration generates a single image (that is no configuration properties are arrays) then the result will still be an array with a single image.

Setup presets in your loader:

{
  module: {
    loaders: [
      {
        test: /\.(gif|jpe?g|png|svg|tiff)(\?.*)?$/,
        loader: 'sharp-loader',
        query: {
          name: '[name].[hash:8].[ext]',
          cacheDirectory: true,
          presets: {
            // Preset 1
            thumbnail: {
              format: ['webp', 'jpeg'],
              width: 200,
              quality: 60,
            },
            // Preset 2
            prefetch: {
              // Format-specific options can be specified like this:
              format: {id: 'jpeg', quality: 30},
              mode: 'cover',
              blur: 100,
              inline: true,
              size: 50,
            },
          },
        },
      },
    ];
  }
}

Use without presets generating a single image:

const images = require('./aQHsOG6.jpg?{"outputs":[{"width": 500}]}');
console.log(images[0].format); // 'image/jpeg'
console.log(images[0].url); // url to image

Use single preset generating multiple images:

const images = require('./aQHsOG6.jpg?{"outputs":["thumbnail"]}');
console.log(images[0].url); // url to first image
console.log(images[1].url); // url to second image

Use multiple presets generating multiple images:

const images = require('./aQHsOG6.jpg?{"outputs":["thumbnail", "prefetch"]}');
console.log(images);

Modify the value in a preset:

const images = require('./aQHsOG6.jpg?{"outputs":[{"preset": "thumbnail", "width": 600}]}');
console.log(images);

Server-Side Rendering

You can disable emitting the image files with:

{
  emitFile: false
}

Complex Example

{
  presets: {
    default: {
      name: (meta) => {
        // If a scaled image is given, include scale in output name
        if (meta.scale) {
          return '[name]@[scale]x.[hash:8].[ext]';
        }
        return '[name].[hash:8].[ext]';
      },
      format: (meta) => {
        // If the image is transparent, convert to webp and png,
        // otherwise just use jpg.
        if (meta.hasAlpha) {
          return ['webp', 'png'];
        }
        return ['webp', {format: 'jpeg', quality: 70}];
      },
      scale: (meta) => {
        // If the image has no intrinsic scaling just ignore it.
        if (!meta.scale) {
          return undefined;
        }
        // Downscale and provide 1x, 2x, 3x, 4x.
        return [1, 2, 3, 4].filter((x) => {
          return x <= meta.scale;
        });
      },
    },
    preview: {
      name: '[name]-preview.[hash:8].[ext]',
      format: (meta) => {
        if (meta.hasAlpha) {
          return 'png';
        }
        return {format: 'jpeg', quality: 40};
      },
      blur: 100,
      inline: true,
      scale: ({width, height}) => {
        // Make a really tiny image.
        return Math.min(50 / width, 50 / height);
      },
    },
  },
}

sharp-loader's People

Contributors

10xjs avatar aesopwolf avatar izaakschroeder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharp-loader's Issues

Setting quality has no impact

Setting the quality option has no impact on filesize e.g. JPEGs

preset: {
  width: 300,
  quality: 50
}

Also the format syntax has no effect.

I'am using sharp: v0.21.3.

Deprecation warning (sharp)

I'am getting a deprecation warning which should be related to sharp version:

(node:27161) DeprecationWarning: crop(position) is deprecated, use resize({ fit: "cover", position }) instead

I'am using sharp v0.21.3.

Webpack 3 support

I've had luck using the plugin with Webpack 3, but that's just my use case. Is it safe to bump the Webpack engine version for now?

Error when trying to load file by import statement with query

I'm working on a project in Gatsby and don't want to mess about with the canned webpack configuration it provides just to load a couple of images.

So I want to use this loader with an import line in the JS file alone, and configure it with query strings.

Is this possible?

So far I'm trying

import image from 'sharp-loader!./test.png?{"outputs":[{"format": "jpg"}]}'

I was hoping this would simply convert the PNG to a JPEG. Ideally I want to specify quality level and have it optimized too.

I'm getting

TypeError: Cannot read property 'context' of null
    at Object.module.exports ([...]/node_modules/sharp-loader/dist/sharp.js:232:29)

Doesn't work with webpack 5 (support needed?)

I think this version does not work with webpack 5. I have the following:

{
  test: /\.(gif|jpe?g|png|svg|tiff)(\?.*)?$/,
  include: [path.resolve(__dirname, 'src/photography')],
  loader: "sharp-loader",
  options: {
    name: "[name].[hash:8].[ext]",
    cacheDirectory: true,
    presets: {
      // Preset 1
      thumbnail: {
        format: ["webp", "jpeg"],
        width: 200,
        quality: 60,
      },
      // Preset 2
      prefetch: {
        // Format-specific options can be specified like this:
        format: { id: "jpeg", quality: 30 },
        mode: "cover",
        blur: 100,
        inline: true,
        size: 50,
      },
    },
  },
},
// Images: Copy image files to build folder
{ test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: 'asset/resource' }

import testImage from '../../photography/fullsizeoutput_203a.jpeg?{"outputs":["thumbnail"]}';

It appears the query parameters are ignored and the result of testImage is undefined. Is this something to do with the new asset modules?

How to use format specific options like progressive

Hey,
loving your loader. Super fast and easy to use. I'm just missing a few options.
I tried to add

jpeg: {
  progressive: true
}

but doesn't change anything. Would be great if that were exposed. Also since sharp prefers quality to be passed as a format specific option.

Error when trying to config chain it to webpack

I'm currently working on a vue project and tried to translate your example config to chainWebpack syntax and include it in my vue.config.js.
This is what i came up with:

module.exports = {
  chainWebpack: config => {
    config.module
        .rule('resize-images')
        .test(/\.(gif|jpe?g|png|tiff)(\?.*)?$/)
        .use('sharp-loader')
            .loader('sharp-loader')
                .query()
                    .name('[name].[hash:8].[ext]')
                    .cacheDirectory(true)
                    .presets()
                        .thumbnail()
                            .format(['webp', 'jpeg'])
                            .width(200)
                            .quality(60)
                .end()
    }
}

Getting following error:

 ERROR  TypeError: config.module.rule(...).test(...).use(...).loader(...).query is not a function

I saw that other loaders in my webpack config used options: instead of
query: and i think thats the issue โ€“ i tried the following and got no more errors:

module.exports = {
  chainWebpack: config => {
    config.module
        .rule('resize-images')
        .test(/\.(gif|jpe?g|png|tiff)(\?.*)?$/)
        .use('sharp-loader')
            .loader('sharp-loader')
                .options()
                .end()
    }
}

I'm currently on [email protected].

Thank you for your work!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.