如何访问 LESS 生成的 AST?
How can I access the AST that LESS generates?
我想通过访问 AST. The programmatic usage 文档对 LESS 样式表执行一些代码分析,仅涵盖如何呈现文件或字符串。
如何访问 less.js AST?
Github user Vecerek had a similar need。 less.parse
可以与回调一起使用来访问 AST:
...I'm putting the actual code here, that works to get the AST, in case someone will be facing the same hurdle and comes across this issue.
var less = require('less')
, fs = require('fs')
, path = require('path');
var src = './test_import.less'; //some less source file
var result = less.parse(fs.readFileSync(src).toString(), {
filename: path.resolve(src)
}, function(e, tree) {
console.log(JSON.stringify(tree, null, 2));
});
这段代码可以合理地改编为使用 promise 结构,我发现它更有用:
function lessAST(filename, options) {
options = options || {};
options.filename = path.resolve(filename);
return new Promise(function (res, rej) {
less.parse(fs.readFileSync(filename).toString(), options, function (e, tree) {
if (e) {
rej(e);
} else {
res(tree);
}
});
});
}
用法示例:
lessAST('styles.less', {
...options...
}).then(function (tree) {
...do stuff with the AST...
});
我想通过访问 AST. The programmatic usage 文档对 LESS 样式表执行一些代码分析,仅涵盖如何呈现文件或字符串。
如何访问 less.js AST?
Github user Vecerek had a similar need。 less.parse
可以与回调一起使用来访问 AST:
...I'm putting the actual code here, that works to get the AST, in case someone will be facing the same hurdle and comes across this issue.
var less = require('less') , fs = require('fs') , path = require('path'); var src = './test_import.less'; //some less source file var result = less.parse(fs.readFileSync(src).toString(), { filename: path.resolve(src) }, function(e, tree) { console.log(JSON.stringify(tree, null, 2)); });
这段代码可以合理地改编为使用 promise 结构,我发现它更有用:
function lessAST(filename, options) {
options = options || {};
options.filename = path.resolve(filename);
return new Promise(function (res, rej) {
less.parse(fs.readFileSync(filename).toString(), options, function (e, tree) {
if (e) {
rej(e);
} else {
res(tree);
}
});
});
}
用法示例:
lessAST('styles.less', {
...options...
}).then(function (tree) {
...do stuff with the AST...
});