前几天在写微信小程序,由于小程序不直接支持SVG标签,所以后来使用PNG作为素材。但是在发布的时候提示包体积超过2M,为了优化包体积与加载速度,于是我开始想办法处理。
var fs = require("fs"); var path = require("path"); //SVG 文件目录 let dirPath = "./svg/"; let styleStr = ""; let htmlStr = ""; let dirs = fs.readdirSync(dirPath); if (dirs.length > 0) { dirs.forEach(function (filename) { let filedir = path.join(dirPath, filename); if (fs.statSync(filedir).isFile()) { var bData = fs.readFileSync(filedir); var base64Str = bData.toString('base64'); var datauri = 'data:image/svg+xml;base64,' + base64Str; let className = filename.split(".")[0]; let iconStyle = ` .${className}{ background-image: url("${datauri}"); background-size: cover; }`; styleStr = styleStr + "\r\n" + iconStyle + "\r\n"; htmlStr = htmlStr + `<div class="box"><div class="svg-icon ${className}"></div><div>${className}</div></div>`; } }); } let demoHtml = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Demo</title> <link rel="stylesheet" href="./svgicon.css"> <style>.box{ width: 200px; margin: 20px 40px; float: left; text-align: center; } .svg-icon { display: inline-block; width: 60px; height: 60px; } </style> </head> <body> ${htmlStr} </body> </html> `; fs.writeFileSync("svgicon.css", styleStr); fs.writeFileSync("demo.html", demoHtml);
转载请注明:有爱前端 » 微信小程序批量导入iconfont下的SVG图片