【问题标题】:How to get full selectors using csstree?如何使用 csstree 获得完整的选择器?
【发布时间】:2021-04-26 23:06:31
【问题描述】:

我只是在学习如何使用 csstree 处理 CSS ast:https://github.com/csstree/csstree

我想提取选择器,我可以再次检查我的 HTML DOM 并仅返回匹配的规则集,但我需要完整的选择器:

例如:

button.primary.login {...}

目前,我正在做以下事情:

const csstree = require('css-tree');

const ast = csstree.parse(`
  button#primary.red, button#primary.orange { color: "red" }
  div#logo { height: "100px" }
`);

selectors = [];
const collector = (node, current) => {
  if (node.data.type === 'TypeSelector') current = current + node.data.name;
  if (node.data.type === 'IdSelector') current = current + `#${node.data.name}`;
  if (node.data.type === 'ClassSelector')
    current = current + `.${node.data.name}`;

  if (!node.next) return selectors.push(current);

  if (node.next) collector(node.next, current);
};

csstree.walk(ast, node => {
  if (node.type === 'Selector') {
    collector(node.children.head, '');
  }
});

console.log(selectors); // [ 'button#primary.red', 'button#primary.orange', 'div#logo' ]

但不确定这是否是最好的方法。有没有更好的方法?

【问题讨论】:

    标签: css data-structures abstract-syntax-tree


    【解决方案1】:

    目前,css-tree 不具备仅解析选定组件的功能(仅像选择器)。

    但如果您只需要选择器名称,您可以通过禁用一些解析选项来提高性能:

    cssTree.parse(code, {
      parseAtrulePrelude: false,
      parseRulePrelude: false,
      parseValue: false
    })
    

    通过禁用这些解析选项,css-tree 将跳过一些不必要的过程,然后编译过程将更加高效和快速。


    参考:

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多