0.4.2 • Published 10 months ago

postcss-background-image-suffix v0.4.2

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

postcss-background-image-suffix

PostCSS 7.x 插件,用于在 CSS background image 中添加扩展参数,使用场景:png 转 WebP 格式追加 CDN 转换参数。

Usage

  1. 修改 postcss.config.js 配置文件:
module.exports = {
  plugins: [
    require('postcss-background-image-suffix')({
      webpPrefixClass: '_webp',
      pngPrefixClass: '_png',
      suffix: '?x-oss-process=image/format,webp',
      specialFilter: {
        webpPrefixClass: '_webp',
        pngPrefixClass: '_png',
        suffix: '?imageMogr2/format/webp',
        projects: ['game'],
      },
    }),
    require('autoprefixer'),
  ],
};
  1. 在 HTML 入口 head 区域添加以下脚本,用于区分当前浏览器是否支持 webp 格式。
<script>
  (function () {
    var img = new Image();
    img.onload = function () {
      var result = img.width > 0 && img.height > 0;
      window.__supportWebp__ = result;
      document.documentElement.classList.add(result ? '_webp' : '_png');
    };
    img.onerror = function () {
      window.__supportWebp__ = false;
      document.documentElement.classList.add('_png');
    };
    img.src = 'data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==';
  })();
</script>

Example

Before:

.foo {
  font-size: 12px;
  position: relative;
  background-image: url(./bg.png);
  background: url(./bg.png) no-repeat;
  background-image: url(data:image/svg+xml;base64,PHN2Z==);
}

.bar {
  background: url(./bg.png) no-repeat;
  background-size: 100% 100%;
  background-position: 0 -1px;
}

After:

.foo {
  font-size: 12px;
  position: relative;
}
._webp .foo {
  background-image: url(./bg.png?x-oss-process=image/format,webp);
  background-image: url(data:image/svg+xml;base64,PHN2Z==);
  background: url(./bg.png?x-oss-process=image/format,webp) no-repeat;
}
._png .foo {
  background-image: url(./bg.png);
  background-image: url(data:image/svg+xml;base64,PHN2Z==);
  background: url(./bg.png) no-repeat;
}

._webp .bar {
  background: url(./bg.png?x-oss-process=image/format,webp) no-repeat;
  background-size: 100% 100%;
  background-position: 0 -1px;
}

._png .bar {
  background: url(./bg.png) no-repeat;
  background-size: 100% 100%;
  background-position: 0 -1px;
}
0.4.2

10 months ago

0.4.1

10 months ago

0.4.0

10 months ago

0.3.4

10 months ago

0.3.3

10 months ago

0.3.2

10 months ago

0.3.1

10 months ago

0.3.0

10 months ago

0.2.0

10 months ago

0.1.0

10 months ago