0.1.1 • Published 26 days ago

@jamais/webp-webpack-plugin v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
26 days ago

webp-webpack-plugin

Convert images to webp and keep the original file name.

Requirements

  • node.js 14+
  • webpack 5+
  • If you are using webpack 4, you may check out the previous version: 0.0.8.

Features

  • Support and only support png and jpg images.
  • If converted file is bigger than original file, skip this file.
  • Auto disabled in development mode.
  • Support ES Module.

Usage

npm install --save-dev @jamais/webp-webpack-plugin

In webpack.config.js

import WebpWebpackPlugin from '@jamais/webp-webpack-plugin';

const options = {
  skipDev: true, // Defaults true, if you want to build webp in development mode, set it false.
  type: ['jpg', 'png'],
  webp: {
    quality: 75
  }
};

export default {
  mode: 'production',
  ...{'Other': 'configurations'},
  plugins: [
    new WebpWebpackPlugin(options)
  ]
};

// output
// [name].[hash].jpg
// [name].[hash].jpg.webp

Constructor parameters

  1. options Object
  2. options.skipDev [Boolean], default: true
  3. options.type [String] | [Array], default: 'jpg', 'png', example: 'jpg', 'png', 'png'
  4. options.min [Number], image which smaller than that will be skipped. Default: 8192(8KB)
  5. options.webp [Object], default & referrer: sharp

Setup the server

In nginx server, you can setup the configurations for example belows.

http {
  # Other configurations

  map $http_accept $webp_suffix {
    default   "";
    "~*webp"  ".webp";
  }

  server {
    # Other configurations

    location ~* /img/.*\.(png|jpg|jpeg)$ {
      add_header Vary Accept;
      try_files $uri$webp_suffix $uri =404;
    }
  }
}

If you prefer client side detection, checkout these steps for references

In html, use picture tag.

<picture>
  <source srcset="/path/to/image.webp" type="image/webp">
  <img src="/path/to/image.jpg" alt="insert alt text here">
</picture>

In css, use @supports

.logo-container {
  background-image: url('logo.jpg');

  @supports (background-image: url('logo.webp')) {
    background-image: url('logo.webp');
  }
}

In javascript and dom, use canvas's toDataURL method or use Image to load a webp image.

const supportWebP = e => document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0;

// Or
function supportsWebP() {
  var img = new Image();
  img.onload = function() {
    return img.width === 2;
  };
  img.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
  return img.onload;
}

Misc:

Checkout what Modernizr did from github. Detect WebP browser support check-webp-support.js CSS Fallbacks for WebP background images with @supports

0.1.1

26 days ago

0.1.0

9 months ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago