A
A
Anton Misyagin2019-02-28 09:35:08
webpack
Anton Misyagin, 2019-02-28 09:35:08

How to use webp in css on webpack?

Repository
webpack 4
In the source code of the project (folder src) are downloaded from the Internet jpg, png. With the help of multi-loader and webp-loader, I convert the image data to the webp version and at the same time save the source. Those. the output is the same (jpg or png) + webp. The rule that describes this process is:

{
        test: /\.(jpe?g|png)$/i,
        loader: multi(
          'file-loader?name=[name]_[hash:7].webp!webp-loader?{quality: 95}',
          'file-loader?name=[name]_[hash:7].[ext]'
        )
      }

I'm using the sass style preprocessor.
When loading resources inside a style file, for example: using the url-loader loader Here is an example of how I access different versions of an image from the markup and it works (pug preprocessor):
src: url('fonts/GothaProLig.otf')
picture
      source(type='image/webp', srcset=require('!!file-loader?name=[name]_[hash:7].webp!./img/as.jpg'))
      img(src=require('!!file-loader?name=[name]_[hash:7].[ext]!./img/as.jpg'))

Now attention to the question, how to describe the process of accessing the webp version of the file inside the style file .
PS:
src: url(require('!!file-loader?name=[name]_[hash:7].webp!./img/as.jpg'))

That doesn't work :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Yeltsov, 2020-05-18
@YellowGreen

First you need to check in the js file if the browser supports the webp format:

function testWebP(callback) {

var webP = new Image();
webP.onload = webP.onerror = function () {
callback(webP.height == 2);
};
webP.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
}

testWebP(function (support) {

if (support == true) {
document.querySelector('body').classList.add('webp');
}else{
document.querySelector('body').classList.add('no-webp');
}
});

and then set the properties in the style file, for example:
.webp div { background: url(../img/image.webp) 0 0 no-repeat; }

There is another option:
https://www.npmjs.com/package/webpack-css-replace-...
but I use the first one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question