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"]);
分类:
javascript
, WEB
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库