webpack优化之image 优化

前言:在一下应用中,可能静态图片就占了应用尺寸的一半,虽然图片的加载不会像js一样阻塞dom的渲染,但是它们的加载却占用了很大的带宽,增加了公司的成本。在webpack中,我们可以使用url-loader,svg-url-loader,image-webpack-loader来进行图片优化。

1、url-loader

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|gif)$/,
        loader: 'url-loader',
        options: {
          // 小于10240字节的图片将被转换成base64嵌入js代码中
          limit: 10 * 1024,
        },
      },
    ],
  }
};
// index.js
import imageUrl from './image.png';
// → If image.png is smaller than 10 kB, `imageUrl` will include
// the encoded image: 'data:image/png;base64,iVBORw0KGg…'
// → If image.png is larger than 10 kB, the loader will create a new file,
// and `imageUrl` will include its url: `/2fcd56a1920be.png`

2、svg-url-loader,svg图片也可以使用url来处理成base64,但是由于svg是一个纯文本文件,所以采用svg-url-loader使用URL encoding处理尺寸会更小

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.svg$/,
        loader: 'svg-url-loader',
        options: {
          // 小于10240的进行URL编码
          limit: 10 * 1024,
          // 移除引号
          // (they’re unnecessary in most cases)
          noquotes: true,
        },
      },
    ],
  },
};

3、image-webpack-loader可以支持JPG, PNG, GIF and SVG 图片的压缩,因为它仅仅是压缩作用,不会讲图片嵌入应用,因此我们需要与url-loader和svg-url-loader一起使用,为了不需要在每个loader里复制一遍image-webpack-loader的配置,我们可单独将其配置在一个规则中,并使用enfore:"pre"让它最先执行。

 // webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        loader: 'image-webpack-loader',
        // This will apply the loader before the other ones
        enforce: 'pre',
      },
    ],
  },
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值