5行代碼的簡易模板解析函數(shù)

不喜歡拼字符串,es6也沒法使用,很捉急
沒辦法只能出大招,自己動手豐衣足食

function simpleTpl(tpl,opts){
    return tpl.replace(/(\{.+?\})/g,function(all,cap1){
        return opts[cap1.replace(/\}|\{/g,"")] || "";
    })
}

舉個栗子

var file="css/index.less";
var command = simpleTpl(
    "lessc {file} {fileNotExt}.css --js -x --source-map={fileNotExt}.css.map",
    {
        file:file,
        fileNotExt:file.split(/\.[^.]+?$/)[0]
    }
)
console.log(command)
//lessc css/file.less css/index.css  --js -x --source-map=css/file.css.map

與沒有使用模板函數(shù)的情況相比,可讀性還是有一定區(qū)別的


var file="css/index.less";
var fileNotExt = file.split(/\.[^.]+?$/)[0];
var command = "lessc "+file+" "+fileNotExt+".css" + 
" --js -x --source-map="+fileNotExt + ".css.map";
console.log(command)
//lessc css/file.less css/index.css  --js -x --source-map=css/file.css.map
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容