一個簡單的 grunt 插件, 做用是 把 css 文件中的 /images/ 替換成指定的 url path, 以實現 圖片 cdn 路勁改造css
插件項目文件結構node
grunt-contrib-staticpath |--tasks |----staticpath.js |--package.json
package.jsongit
{ "name": "grunt-contrib-staticpath", "version": "1.0.2", "description": "A grunt plugin to help front engineer replacing public static path of css.", "main": "tasks/staticpath.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git@192.168.1.22:node/grunt-contrib-staticpath.git" }, "keywords": [ "grunt-contrib-staticpath" ], "author": "ecalf", "license": "ISC" }
staticpath.js
var path = require('path'); module.exports = function (grunt) { "use strict"; grunt.registerMultiTask('publicPath', 'Replace publicPath of image and update the CSS file.', function () { var done = this.async(); var options = this.options({ imagepath:"/images/", imagepathPublic:"//node-img.b0.upaiyun.com/wmzy-pc/images/" }); //console.log("options>>>",options); //console.log("this.files>>>",this.files) function replaceCSSImagesPath(cssData){ var oldPath = options.imagepath; var newPath = options.imagepathPublic; var reg = new RegExp('url\\(\\s*([\\\'\\\"])?'+oldPath,'gi'); //console.log("todo reg:",reg) cssData = cssData.replace(reg,'url($1'+newPath); //console.log("done cssData.replace"); //console.log('indexOf ',newPath,': ',cssData.indexOf(newPath)); return cssData } function donePathReplace(cssData, destCSS){ grunt.file.write(destCSS, cssData); grunt.log.writelns(('Done! [Replace publicPath of image, Created] -> ' + destCSS)); } function staticPathIterator(file, callback){ var src = file.src[0]; var fileName = path.basename(src, '.css'); var destCSS = file.dest; var cssData = grunt.file.read(src); var newCssData = replaceCSSImagesPath(cssData); donePathReplace(newCssData, destCSS); callback(null); } grunt.util.async.forEachSeries(this.files, staticPathIterator, function(success){ done(success); }); }); };
使用時在 Gruntfile.js 中的配置json
publicPath:{ options:{ imagepath:"/images/", imagepathPublic:"//node-img.b0.upaiyun.com/wmzy-pc/images/" }, autoPublicPath:{ files: [ { expand: true, cwd: "public/src/css/", src: "**/*.css", dest: "public/src/css/" } ] } },
用法:async
grunt.loadNpmTasks('grunt-contrib-staticpath'); //test task grunt.registerTask('test',["publicPath"]);