postcss-background-image-suffix
TypeScript icon, indicating that this package has built-in type declarations

0.4.2 • Public • Published

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;
}

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
0.4.23latest

Version History

VersionDownloads (Last 7 Days)Published
0.4.23
0.4.11
0.4.01
0.3.40
0.3.20
0.3.10
0.3.00
0.2.01
0.1.00

Package Sidebar

Install

npm i postcss-background-image-suffix

Weekly Downloads

6

Version

0.4.2

License

MIT

Unpacked Size

20.7 kB

Total Files

5

Last publish

Collaborators

  • isunkui