node.js - 如何访问 LESS 生成的 AST?

标签 node.js less abstract-syntax-tree

我想通过访问 AST 对 LESS 样式表执行一些代码分析。 programmatic usage文档仅介绍如何渲染文件或字符串。

如何访问less.js谷草转氨 enzyme ?

最佳答案

Github user Vecerek had a similar needless.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/

相关文章:

从语法中提取标记

javascript - 使用 alert() 的 Sonar 编码规则

node.js - Electron 客户端IP

compiler-construction - Aptana Studio 3 是否支持较少的 css 编译?

css - 在另一个 mixins 中更改 mixins 参数

javascript - LESS 和自动 CSS 缓存

abstract-syntax-tree - 在 xtext 中查看解析树/节点模型/AST

node.js - 如何在 mongoose 中使用嵌套模式(使用 'type' )来创建数组?

database - 使用 Node.js 进行同步数据库查询

javascript - Selenium 截图不保存指定目录