UNPKG

@tripmini/font-compression-plugin

Version:

基于font-spider的一款字体压缩插件,通过此插件可实现vue项目打包时对特殊字体的自动化压缩

34 lines (33 loc) 2.81 kB
function compileHTML(e){let t="";return e.forEach(e=>{t+=`<div class='${e.className}'>${e.content}</div>`}),t}function compileCSS(e,t){let o="";return e.forEach(e=>{o+=t?`@font-face { font-family:'${e.fontName}'; src: url('./${e.fontName}.woff') format('woff'), url('./${e.fontName}.woff2') format('woff2'), url('./${e.fontName}.ttf') format('truetype'); font-display: swap; } .${e.className} { font-family: '${e.fontName}'; }`:`@font-face{ font-family:'${e.fontName}'; src: url('./${e.fontName}.ttf') format('truetype'); font-display: swap; } .${e.className} { font-family: '${e.fontName}'; }`}),o}const fontSpider=require("font-spider"),fs=require("fs"),path=require("path"),HTML_TEMPLATE=`<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./font.css"> <title>font-compression-template</title> </head> <body> <!-- html inner --> </body> </html> `,HTML_INNER_MARK="\x3c!-- html inner --\x3e",CSS_INNER_MARK="/* css inner */",createFileHTML=(o,e,s)=>{const r=""+s+e;return new Promise(t=>{fs.mkdir(path.resolve(s),{recursive:!0},e=>{e?t(e):fs.writeFile(r,o,e=>{e?console.log("error>> :",e):console.log("HTMLTemplate created successfully"),t(e)})})})},createFileCSS=(o,e)=>{const s=e+"font.css";return new Promise(t=>{fs.mkdir(path.resolve(e),{recursive:!0},e=>{e?t(e):fs.writeFile(s,o,e=>{e?console.log("error>> :",e):console.log("CSSTemplate created successfully"),t(e)})})})},copyFontFile=(e,s)=>{e.forEach(t=>{var e=path.resolve(t.fontDir)+".ttf",o=path.resolve(__dirname,`${path.resolve(s)}/${t.fontName}.ttf`);fs.copyFile(e,o,0,e=>{if(e)throw console.log("copy error>> :",e),e;console.log(`copy ${t.fontName} successfully`)})})};class FontCompressionPlugin{constructor({fontList:e,htmlFile:t,baseUrl:o,isProEnv:s}){if(!e)throw new Error("Please input your font list!");this.fontList=e,this.htmlFile=t||"font.html",this.baseUrl=o||"src/assets/font/",this.isProEnv=s||!1}apply(e){e.hooks.afterPlugins.tap("@tripmini/font-compression-plugin",async()=>{await copyFontFile(this.fontList,this.baseUrl);var e=compileHTML(this.fontList),t=compileCSS(this.fontList,this.isProEnv);const o=HTML_TEMPLATE,s=CSS_INNER_MARK;var e=o.replace(HTML_INNER_MARK,e),t=s.replace(CSS_INNER_MARK,t);await createFileHTML(e,this.htmlFile,this.baseUrl),await createFileCSS(t,this.baseUrl),this.isProEnv&&(e=path.resolve(this.baseUrl)+"/"+this.htmlFile,await fontSpider.spider([e],{silent:!1}).then(function(e){return fontSpider.compressor(e,{backup:!0})}).then(function(e){console.log("webFonts>> :",e)}).catch(function(e){console.error(e)}))})}}module.exports=FontCompressionPlugin; //# sourceMappingURL=index.js.map