我想通过访问 AST 对 LESS 样式表执行一些代码分析。 programmatic usage文档仅介绍如何渲染文件或字符串。
如何访问less.js谷草转氨 enzyme ?
最佳答案
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...
});
关于node.js - 如何访问 LESS 生成的 AST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227715/