WEB项目构建优化之自动清除CSS中的图片缓存

在web项目构建发布时,经常遇到css中图片的修改优化,那么如何清除图片的缓存成为必须要解决的问题。曾经有过傻傻的方法就是直接在图片后面添加随机数。今天主要是从构建自动化方式来解决这个问题,提高开发及发布的效率,让项目向工程化方向靠拢。

在解决这个前,也陆续找了许多方案,像gulp-modify-css-urls,feWorkflow,还有淘宝的一款工具,不过找不到源代码,不知是否开源,要么是不满足,要么就是太重。于是决定参考gulp-modify-css-urls,基于gulp写了一个简单又满足需求的gulp模块来完成这件事情,命名为:gulp-custom-css-urls。

这个模块满足下面需求:

  • 开发和生产环境代码分开。
  • 构建发布自动化。
  • 跳过图片地址是data:;base64格式。
  • 跳过http,https等网络能直接访问的地址。
  • 支持输出图片,以便上传至CDN。

用法:

var customCssUrls = require('gulp-custom-css-urls');
var gulp = require('gulp');
var path = require('path');
gulp.task('demo',function(){
  return gulp.src('assets/**/*.css')
    .pipe(customCssUrls({
      /** 
       * static filepath relative absolute filepath's physical position. 
       * eg: 
       * image path inline css is '/images/demo.png', 
       * image absoulte filepath is '/Users/Navy/Desktop/code/demo/assets/images/demo.png', 
       * the process(process.cwd()) path is '/Users/Navy/Desktop/code/demo', 
       * so the image path relative website root path is 'assets/'
      */
      staticfile_relative_website_rootpath: 'assets/', 
      outputImage: true, // output images file , default to false
      outputImage_path: './.gulp_dist_output_images', // default to './.gulp_dist_output_images'
      modify: function (imageRelativePath, cssFilePath, imageRelativeWebsiteRootPath, imgInfo) {
        // modify image url before prepend or append
        // the imgInfo param is object, {hash: 3503865059, width: 1782, height: 530, orgin_filename: 'custom.png'}
        return path.join(imageRelativeWebsiteRootPath, path.basename(imageRelativePath)); //let the relative path become an absolute path
      },
      prepend: '', // prepend string before image url
      append: '', // append string after image url
      processPath: process.cwd() // custom process path , default to process.cwd()
    }))
    .pipe(gulp.dest('tmp/'));
})
gulp.task('default',['demo']);

源码地址:https://github.com/navyxie/gulp-custom-css-urls

用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值