grunt 插件

一个简单的 grunt 插件, 作用是 把 css 文件中的  /images/  替换成指定的  url path, 以实现 图片 cdn 路劲改造

插件项目文件结构

grunt-contrib-staticpath
|--tasks
|----staticpath.js
|--package.json

package.json

{
"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 中的配置

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/"
}
]
} },

用法:

grunt.loadNpmTasks('grunt-contrib-staticpath');

//test task
grunt.registerTask('test',["publicPath"]);
上一篇:[smartMenu.js] 一个基于jquery的实用的右键拓展菜单栏插件


下一篇:【BZOJ2095】【POI2010】Bridge 网络流