在web項目構建發佈時,常常遇到css中圖片的修改優化,那麼如何清除圖片的緩存成爲必需要解決的問題。曾經有過傻傻的方法就是直接在圖片後面添加隨機數。今天主要是從構建自動化方式來解決這個問題,提升開發及發佈的效率,讓項目向工程化方向靠攏。css
在解決這個前,也陸續找了許多方案,像gulp-modify-css-urls,feWorkflow,還有淘寶的一款工具,不過找不到源代碼,不知是否開源,要麼是不知足,要麼就是過重。因而決定參考gulp-modify-css-urls,基於gulp寫了一個簡單又知足需求的gulp模塊來完成這件事情,命名爲:gulp-custom-css-urls。git
### 這個模塊知足下面需求:github
- 開發和生產環境代碼分開。
- 構建發佈自動化。
- 跳過圖片地址是data:;base64格式。
- 跳過http,https等網絡能直接訪問的地址。
- 支持輸出圖片,以便上傳至CDN。web
### 用法:gulp
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緩存