2012-03-17 79 views
5

我可以解析LESS客户端,并返回结果吗?解析LESS客户端

我目前正在使用中的文件,这是包括更少的文件,以及精缩少解析器之后建议。我想能够返回原始的CSS,所以我可以将它保存为一个CSS文件。

我不想安装node.js等,我想要一个客户端解决方案。

+0

对于有你名誉的人来说,虐待是很残酷的。 – 2012-03-17 02:38:20

+0

错误?那是什么意思? – 2012-03-17 02:44:58

+1

@MK .:你是什么意思? '少'是适当的标签。 – Blender 2012-03-17 02:45:01

回答

11

一看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设置地点的误差参数的属性的任何更好的文档。

+0

正是我正在寻找,工作的一种享受,谢谢。我有点惊讶这是客户端脚本的一个未记录的功能,因为它是这样一个基本和平凡的功能。这意味着即使当我在iPad上离线时,或者在其他计算机上只能访问基于浏览器的工具时,我也可以轻松地使用较少的来源。快乐的时光。再次感谢〜) – 2012-03-17 12:04:23

+0

原来这个方法被记录下来(几乎相同),但是对于服务器端。在客户端也可以正常工作。 – 2012-03-17 12:40:25

0

@ 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为它工作:)

1

这里是一个工作示例: https://jsfiddle.net/y0oss091/1/

less.render("p{color: #ff66ff}") 
    .then(function(output) { 
     console.log(output.css) 
    }, 
    function(error){}); 

从CDN加载的文件较少。

那里有很多资源。
但是,我不确定客户端使用比安装npm和节点更容易。

相关问题