我可以解析LESS客戶端,並返回結果嗎?解析LESS客戶端
我目前正在使用中的文件,這是包括更少的文件,以及精縮少解析器之後建議。我想能夠返回原始的CSS,所以我可以將它保存爲一個CSS文件。
我不想安裝node.js等,我想要一個客戶端解決方案。
我可以解析LESS客戶端,並返回結果嗎?解析LESS客戶端
我目前正在使用中的文件,這是包括更少的文件,以及精縮少解析器之後建議。我想能夠返回原始的CSS,所以我可以將它保存爲一個CSS文件。
我不想安裝node.js等,我想要一個客戶端解決方案。
一看less.js source帶來了Parser
對象。假設less.js
包含在頁面:
var data = "@colour: red; #example { background-color: @colour; }",
parser = new less.Parser({});
parser.parse(data, function (error, root) {
// code that handles the parsed data here...
// e.g.:
console.log(root.toCSS());
});
將輸出以下控制檯:
#example {
background-color: #ff0000;
}
爲less.Parser
的構造其實需要一系列的設置,我不理解不夠的LESS的內部說明什麼可能是好傳遞(儘管它們都是可選的,所以傳遞任何都不應該只使用默認值)。
的Parser.parse
方法有兩個參數:含有LESS文件的字符串,並處理該解析數據的回調。該回調最多接收兩個參數,一個錯誤對象(error
)和一個表示解析的LESS(root
)的對象。如果發生致命錯誤,則不通過root
,如果沒有錯誤,則error
將爲null
。
不幸的是,我找不到比他們在源here設置地點的誤差參數的屬性的任何更好的文檔。
正是我正在尋找,工作的一種享受,謝謝。我有點驚訝這是客戶端腳本的一個未記錄的功能,因爲它是這樣一個基本和平凡的功能。這意味着即使當我在iPad上離線時,或者在其他計算機上只能訪問基於瀏覽器的工具時,我也可以輕鬆地使用較少的來源。快樂的時光。再次感謝〜) – 2012-03-17 12:04:23
原來這個方法被記錄下來(幾乎相同),但是對於服務器端。在客戶端也可以正常工作。 – 2012-03-17 12:40:25
@ dbaupp的答案是巨大的幫助我,但我沒有找到錯誤處理是如何在他的回答中描述。
我發現少解析客戶端時,而不是傳遞到錯誤參數這意味着你可以將它們解析回調中未反應而被拋出的錯誤。
// I too have no idea what to pass to less.Parser
// but none of them seemed very useful for this
// reading through the source
var parser = new less.Parser({}),
toparse = '.foo {color: red;}';
try {
parser.parse(function (error, root) {
var css = root.toCSS();
console.log(css);
});
} catch (e) {
// if we hit a 404 when importing a less file
// this is only thrown at the end of all the imports
// rather than as soon as it find one broken @import
if (e.name === 'TypeError' && e.message === "Cannot call method 'toCSS' of undefined") {
// handle typeerror here
// if there's a parse error
// assuming your original less file is just some @imports
// this will also tell you which file contains the error
} else if (e.line) {
// the url of the imported file
console.log(e.filename);
// the line containing the error
console.log(e.line);
// this is a 3 item array containing the line with the error
// +/- 1 line either side
// e.extract[1] will be your error
console.log(e.extract);
// this is the error message
console.log(e.message);
} else {
// it broke some other way
// I haven't had this happen to me yet
// so you'll have to figure it out for yourself ;)
}
}
由於情況可能是有用的,我的應用程序增加了對少mediawiki,在這裏我不能訪問任何服務器端,但可以訪問該網站的CSS和JS文件支持的一個例子。我可以分析自己少與新鮮解析少的意思,我需要JS啓用誰是唯一一個替換現有的CSS爲它工作:)
這裏是一個工作示例: https://jsfiddle.net/y0oss091/1/
less.render("p{color: #ff66ff}")
.then(function(output) {
console.log(output.css)
},
function(error){});
從CDN加載的文件較少。
那裏有很多資源。
但是,我不確定客戶端使用比安裝npm和節點更容易。
對於有你名譽的人來說,虐待是很殘酷的。 – 2012-03-17 02:38:20
錯誤?那是什麼意思? – 2012-03-17 02:44:58
@MK .:你是什麼意思? '少'是適當的標籤。 – Blender 2012-03-17 02:45:01